Rails 5 个嵌套属性未保存更新

Rails 5 nested attributes not saving update

我有两个具有嵌套属性的模型。我的表单可以更新书籍:标题,但不能更新嵌套属性。提交后,我看到参数正在进入终端,但没有回滚 (0.2ms)begintransaction (0.2ms)commit transaction.

我花了一整天的时间来解决这个问题,我在模型中尝试了 inverse_ofoptional: trueautosave: true。但仍然无法保存更新。也没有不允许的参数错误。还有一个问题。

型号:

has_many :pages
accepts_nested_attributes_for :pages

控制器:

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

我的表格:

<%= 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 %>

示例控制台结果:

book = Book.first
book.update(title:"test", pages_attributes: [id: 124142 , book_id: 1, state: 1 ])
   (0.2ms)  begin transaction
   (0.2ms)  commit transaction

编辑

服务器日志:

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)

你能试试f.fields_for :pages, @book.pages.build do |builder|吗? 我不是 100% 确定这会起作用,但一段时间前我在字段方面遇到了同样的问题,这就是我修复它的方法。