【问题标题】:Creating associated model with rails使用导轨创建关联模型
【发布时间】:2016-06-20 11:20:47
【问题描述】:

我正在尝试使用 Rails 创建关联模型。我的模型是具有许多文档的财务模型和属于财务的文档。创建关联模型时的工作代码可能是

def create
  @financial = Financial.find(2)
  @document = @financial.documents.create(document_params)
  ...
end

在我看来,我有一个看起来像这样的表格来选择正确的财务

<%= form_for Document.new do |f| %>
<%= f.collection_select :financial_id, Financial.all, :id, :description %>
<%= f.submit %>

当我提交表单时,我确实在日志中看到了正确的参数传输

"financial_id"=>"3"

所以我想我只需要将初始代码更改为:

def create
  @financial = Financial.find(params[:financial_id])
  @document = @financial.documents.create(document_params)
  ...
end

但我收到“找不到带有 'id'= 的财务信息。我尝试了其他方法,包括:

  @financial = Financial.find_by(id: params[:financial_id])

没有太大的成功。谁能给我适当的语法吗?谢谢。

【问题讨论】:

  • 你可以为 document_params 写代码吗?
  • 是的,也许是strong parameters 问题?您是否允许在 Document 上使用 :financial_id?

标签: ruby-on-rails model model-associations


【解决方案1】:

找不到具有“id”=的财务

因为,提交的params实际上是在document哈希里面。所以params[:financial_id] 不起作用。相反,您需要使用params[:document][:financial_id]

def create
  @financial = Financial.find(params[:dcument][:financial_id])
  @document = @financial.documents.create(document_params)
  ...
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多