Rails 5嵌套属性不保存更新

时间:2017-07-05 18:25:01

标签: ruby-on-rails ruby ruby-on-rails-5 nested-attributes

我有两个嵌套属性的模型。我的表单可以更新book:title,但不能更新嵌套属性。在我提交之后,我看到paramaters正在终端,但没有回滚(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)

1 个答案:

答案 0 :(得分:2)

你能试试f.fields_for :pages, @book.pages.build do |builder|吗? 我不是100%肯定这会起作用,但我对领域的问题有同样的问题,这就是我修复它的方法。