【发布时间】:2013-12-04 17:41:25
【问题描述】:
在过去的几天里,我在谷歌上搜索并尝试了我能想到的一切来解决 has_and_belongs_to_many 关系的一个相对简单(我认为)的问题。
我成功地使用 HABTM 关系提交了一个关系值。这是示例代码:
型号:
class Livre < ActiveRecord::Base
has_and_belongs_to_many : auteurs
end
class Auteur < ActiveRecord::Base
has_and_belongs_to_many :livres
end
控制器:
def new
@livre = Livre.new
@auteurs = Auteur.all
end
def create
@livre = Livre.new(livre_params)
if @livre.save
redirect_to [:admin, @livre]
else
render 'new'
end
end
private
def livre_params
params.require(:livre).permit(:name, :auteur_ids)
end
查看:
<% f.label :auteur %><br>
<% f.collection_select(:auteur_ids, @auteurs, :id, :name) %>
发布的参数:
{"utf8"=>"✓",
"authenticity_token"=>"mAXUm7MRDgJgCH00VPb9bpgC+y/iOfxBjXSazcthWYs=",
"livre"=>{"name"=>"sdfsdfd",
"auteur_ids"=>"3"},
"commit"=>"Create Livre"}
但是当我尝试将“multiple true”添加到视图的collection_select 助手时,(现在是多个)关系不再被保存。示例代码:
(模型和控制器均不变)
查看:
<% f.label :auteur %><br>
<% f.collection_select(:auteur_ids, @auteurs, :id, :name, {}, {:multiple => true}) %>
发布的参数:
{"utf8"=>"✓",
"authenticity_token"=>"mAXUm7MRDgJgCH00VPb9bpgC+y/iOfxBjXSazcthWYs=",
"livre"=>{"name"=>"sdfsdf",
"auteur_ids"=>["1",
"5",
"3"]},
"commit"=>"Create Livre"}
如您所见,“auteur_ids”的参数现在是一个数组。这是唯一的区别。
我做错了什么?
澄清一下:两段代码都能够将新记录添加到livres db 表中,但只有第一个代码能够将适当的记录添加到auteurs_livres db 表中。第二个根本没有在auteurs_livres 中插入任何东西。
(我在 ruby 1.9.3p194 和 rails 4.0.1 上运行)
谢谢!
回答
对于遇到同样问题的优秀人士,答案如下:
编辑您的控制器并将允许的参数从 :auteur_ids 更改为 {:auteur_ids => []}
params.require(:livre).permit(:name, {:auteur_ids => []})
它现在可以工作了:)
【问题讨论】:
-
已编辑为两个代码示例添加已发布的参数。
-
很好——你有没有考虑过使用
accepts_nested_attributes_for? -
@RichPeck 不,但我要看看它。谢谢。
-
我本来打算为它写一个答案,但如果你要调查,那就太酷了!让我知道您是否需要提供一些想法的答案
-
@RichPeck 请贡献。我对 rails 和 ruby 还是很陌生,感谢任何指导:)
标签: ruby-on-rails ruby