我有一个表格,让我创造新的博客文章,我希望能够创建相同的形式新类别。HABTM关系和accepts_nested_attributes_for
我有帖子和类别之间的关系,这就是为什么我遇到麻烦。
我有以下2种型号:
class Post < ActiveRecord::Base
has_and_belongs_to_many :categories
attr_accessible :title, :body, :category_ids
accepts_nested_attributes_for :categories # should this be singular?
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
attr_accessible :name
end
我的形式让我从一堆现有类别中挑选,或创建一个全新的。我的表格如下。
# using simple_form gem
.inputs
= f.input :title
= f.input :body
# the line below lets me choose from existing categories
= f.association :categories, :label => 'Filed Under'
# I was hoping that the code below would let me create new categories
= f.fields_for :category do |builder|
= builder.label :content, "Name"
= builder.text_field :content
当我提交我的表单时,它会被处理,但不会创建新的类别。我的命令提示符下输出告诉我:
WARNING: Can't mass-assign protected attributes: category
但是,如果我添加attr_accessible :category
,我得到错误消息的大胖子崩溃“未知属性:类别”。
如果我将fields_for target更改为:categories(而不是category),那么我的表单甚至不会显示。
我花了一段时间试图弄清楚这一点,并观察了nested_models和simple_form上最近的railscasts,但无法解决我的问题。
如果我使用has_many:through关系(使用连接模型)而不是habtm,会更容易吗?
http://stackoverflow.com/a/12961298/1446551 – 2013-04-30 07:48:05