Reputation: 131
I have two models with nested attributes. My form can update book :title, but not nested attributes. After I submit i see paramaters is going in terminal but there is no rollback just (0.2ms)begintransaction (0.2ms)commit transaction.
I spent whole day to solve that, i tried inverse_of
, optional: true
, autosave: true
in models. But still not able save update. Also there is no unpermitted paramater error. There is another problem.
Model:
has_many :pages
accepts_nested_attributes_for :pages
Controller:
def update
if @book.update_attributes(book_params)
redirect_to @book
else
render 'edit'
end
end
def book_params
params.require(:book).permit(:title, pages_attributes: [:id, :state])
end
My form:
<%= form_for(@book) do |f| %>
<%= f.label :title %>
<%= f.text_field :title, :autofocus => true, class: 'form-control' %>
<%= f.fields_for :pages do |builder| %>
<%= builder.select(:state, options_for_select({ "close" => 0, "open" => 1, })) %>
<% end %>
<%= f.submit 'Submit', %>
<% end %>
Example console result:
book = Book.first
book.update(title:"test", pages_attributes: [id: 124142 , book_id: 1, state: 1 ])
(0.2ms) begin transaction
(0.2ms) commit transaction
EDIT
Server log:
Started PATCH "/book/firstbook" for 127.0.0.1 at 2017-07-05 21:57:37 +0300
Processing by booksController#update as HTML
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"pElKKQq+M/5GuEG6nJ6Ac1vkEHyIknA2vPiDC9ND+50tq34nDtCRRX9k6TxaMZCInufp68m6BnO8jt4BsJ1bFg==",
"book"=>{
"title"=>"firstbook",
"pages_attributes"=>{
"0"=>{"state"=>"0", "id"=>"1"},
"1"=>{"state"=>"0", "id"=>"2"},
"2"=>{"state"=>"0", "id"=>"3"},
"3"=>{"state"=>"0", "id"=>"4"},
"4"=>{"state"=>"0", "id"=>"5"},
"5"=>{"state"=>"0", "id"=>"6"},
"6"=>{"state"=>"0", "id"=>"7"},
"7"=>{"state"=>"0", "id"=>"8"},
"8"=>{"state"=>"0", "id"=>"9"},
"9"=>{"state"=>"0", "id"=>"10"},
}
},
"commit"=>"submit", "id"=>"firstbook"
}
book Load (0.2ms) SELECT "books".* FROM "books" WHERE "books"."slug" = ? ORDER BY "books"."id" ASC LIMIT ? [["slug", "firstbook"], ["LIMIT", 1]]
(0.1ms) begin transaction
(0.1ms) commit transaction
Redirected to http://localhost:3000/book/firstbook
Completed 302 Found in 48ms (ActiveRecord: 0.5ms)
Upvotes: 4
Views: 2549
Reputation: 2157
Could you try f.fields_for :pages, @book.pages.build do |builder|
?
I'm not 100% sure this will work but I had the same problem with fields for a while back and this is how I fixed it.
Upvotes: 2