我有两个独立的“组件”模型,联系人和文章。联系人有多种类型(生产者,出口商等......)。
在新文章表单中,我有一个带联系人(ID和标题)的下拉选择器,并希望在文章表中存储选定的值和文本。
在新文章表单视图中:
<%= f.select :producer_id, options_for_select(producers, @article.producer_id) %>
可行,producer_id
存储在文章表中。
这对我来说很明确和合乎逻辑,但在某些情况下,我还需要在producer_title
中存储所选联系人的标题。
我已经阅读了许多不同的选项,例如“在模型中执行,在保存之前”或“在控制器中执行”,并且我已在控制器内完成。
文章控制器(仅来自更新的部分):
#cont_name is producer title from Contacts
def update
params[:article][:producer_title] = Contact.where(id: params[:article][:producer_id]).pluck(:cont_name).first
end
这有效,但这是解决此问题的最佳做法吗?
另外,如果我将params[producer_id]
部分改为使用id: params[:producer_id]
,我为什么无法使其工作?
致以最诚挚的问候和感谢。
答案 0 :(得分:0)
如下所示:
def edit
@article = Article.find(params[:id])
@producers = Contact.where(type: "producer") # or however you distinguish between producers and other contacts
end
然后在您的表单中将其更改为:
f.select :producer_id, options_from_collection_for_select(@producers, "cont_name")
# you might need to do (@producers, "cont_name", "cont_name"), can't quite remember
然后您的更新操作将更加简单:
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article])
...
else
...
end
end
:id => params[:producer_id]
不起作用的原因是params
是嵌套的哈希,所以类似于:
params = { :article => { :producer_id => 34, :title => "Cool Article" }, :another_key => { :key => :value } }
因此,要访问producer_id
,您首先必须检索article
哈希,否则它只会查看包含article
和another_key
的第一组密钥。上面的例子,但不包括producer_id
。