我有两个独立的“组件”模型,联系人和文章。联系人有多种类型(生产商、导出商等...)。
在新文章表单中,我有一个带有联系人(id 和标题)的下拉选择器,我想将所选的值和文本存储在文章表中。
在新文章表单 View 中:
<%= f.select :producer_id, options_for_select(producers, @article.producer_id) %>
有效,producer_id
存储在 article 表中。
这对我来说很清楚也很合乎逻辑,但在某些情况下,我还需要将所选联系人的职位存储在 producer_title
中。
我读过许多不同的选项,例如“在模型中执行,保存前”或“在 Controller 中执行”,并且我已经在 Controller 中完成了。
文章 Controller (仅来自更新的部分):
#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]
,为什么我无法让它工作?
致以最诚挚的问候和感谢。
最佳答案
不如像下面这样的东西:
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
那么你的更新 Action 就会简单很多:
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
.
关于ruby-on-rails - Rails 3,在 Controller 中更改或填写提交的表单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15983728/