[英]Rails 3, change or fill submitted form values in controller
I have two independent "component" models, contacts and articles. 我有两个独立的“组件”模型,联系人和文章。 Contacts come in many types (producers, exporters etc...).
联系人有多种类型(生产商,出口商等)。
In the new article form I have a dropdown selector with contacts (id and title) and want to store the selected value and text in the article table. 在新的文章表单中,我有一个带有联系人(id和标题)的下拉选择器,并希望将所选的值和文本存储在文章表中。
In the new article form view: 在新的文章表单视图中:
<%= f.select :producer_id, options_for_select(producers, @article.producer_id) %>
That works and producer_id
is stored in article table. 可行,并且
producer_id
存储在商品表中。
That's clear and logical to me, but in some cases I also need to store the selected contact's title in producer_title
. 这对我来说很清楚且合乎逻辑,但是在某些情况下,我还需要将所选联系人的标题存储在
producer_title
。
I have read many different options like "do it in model, before save", or "do it in controller", and I have done it inside controller. 我已经阅读了许多不同的选项,例如“在保存之前在模型中完成”或“在控制器中完成”,而我已经在控制器内部完成了。
Article controller (only part from update): 文章控制器(仅更新的一部分):
#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
This works, but is it the best-practices approach to this problem? 这行得通,但这是解决此问题的最佳实践方法吗?
Also, why I can't get it to work if I change the params[producer_id]
part to use: id: params[:producer_id]
? 另外,如果将
params[producer_id]
部分更改为要使用的话,为什么我不能使它工作: id: params[:producer_id]
?
Best regards and thanks. 最好的问候和感谢。
How about something like the following instead: 像下面这样的事情怎么样:
def edit
@article = Article.find(params[:id])
@producers = Contact.where(type: "producer") # or however you distinguish between producers and other contacts
end
Then in your form change it to: 然后以您的形式将其更改为:
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
Then your update action will be much simpler: 然后,您的更新操作将简单得多:
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article])
...
else
...
end
end
The reason :id => params[:producer_id]
doesn't work is that params
is a nested hash, so something like: :id => params[:producer_id]
不起作用的原因是params
是嵌套的哈希,所以类似:
params = { :article => { :producer_id => 34, :title => "Cool Article" }, :another_key => { :key => :value } }
So to access the producer_id
you first have to retrieve the article
hash, otherwise it will only look through the first set of keys which include article
and another_key
in the example above, but don't include producer_id
. 所以访问
producer_id
您必须首先检索article
散,否则只会通过第一组按键,包括看article
和another_key
在上面的例子中,但不包括producer_id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.