Rails 3:无法批量分配嵌套属性

时间:2012-10-01 19:05:40

标签: ruby-on-rails-3 nested-forms nested-attributes

我收到了臭名昭着的错误:

Can't mass-assign protected attributes: comments

据我所知,我已经在我的模型中做了一切:

class Book < ActiveRecord::Base
  attr_accessible :author, :edition, :issue, :title, :url, :comments_attributes
  has_many :comments, :dependent => :destroy
  accepts_nested_attributes_for :comments, :allow_destroy => true
end

并查看:

<%= form_for @book, :remote => true do |f| %>
  <%= f.label :title %>:
  <%= f.text_field :title %><br />

  <%= f.label :author %>:
  <%= f.text_field :author %><br />

  <%= f.fields_for @comment do |comment| %>
  <%= comment.label :body, :Comment %>:
  <%= comment.text_area :body %><br />
  <% end %>

  <%= f.submit %>
<% end %>

我在这里缺少什么?我已经阅读了关于stackoverflow的十几个类似的问题,但是那里唯一的建议似乎是添加attr_accessible和accepts_nested_attributes_for,这两个我已经得到了。当然还有其他的东西吗?

1 个答案:

答案 0 :(得分:3)

你有fields_for @comment do | comment | 它应该是:

fields_for :comments do |comment|

然后在下一行中,我可能只会使用字符串“Comment”作为标签。