我通过与我的模型关联设置了一个 has_many ,并且我正在尝试创建一个表单,可以在其中向提交的歌曲添加多种流派。我正在为此使用 collection_select 助手。以下是有关如何设置我的代码的片段。
歌曲模型
has_many :song_genres
has_many :genres, :through => :song_genres
类型模型
has_many :song_genres
has_many :songs, :through => :song_genres
歌曲流派模型
belongs_to :song
belongs_to :genre
然后在我的new.html.erb中 我有这个
collection_select :song, :genres, Genre.all, :id, :name, {:selected => 1}, {:multiple => true}
当我提交表单时,我会得到一个
Can't mass-assign protected attributes: genres
错误
我知道我在这里错过了一些大事。有人可以帮助我如何正确设置它吗?
谢谢!
最佳答案
试试这个方法:
collection_select :song, :genre_id, Genre.all, :id, :name, {:selected => 1}, {:multiple => true}
如 Rails guide 中所述: “如果您使用 select(或类似的帮助程序,例如 collection_select、select_tag)来设置 own_to 关联,则必须传递外键的名称(在上面的示例中 city_id),而不是关联本身的名称。”
关于ruby-on-rails - 通过使用 Rails 将 collection_select 与 has_many 一起保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9761031/