Search code examples
ruby-on-railsmodelmodel-associations

Creating associated model with rails


I am trying to create associated models with Rails. My models are Financial which have many documents and Document which belongs to Financial. A working code when creating the associated model could be

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

In my view I have a form which looks like this to select the right Financial

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

I do see the right parameters being transferred in the log when I submit the form

"financial_id"=>"3"

So I figured I would just need to change the initial code to:

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

but I get a "Couldn't find Financial with 'id'=". I have tried other things including:

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

Without much success. Could anyone give me the appropriate syntax please? Thanks.


Solution

  • Couldn't find Financial with 'id'=

    Because, the params that are submitted are actually inside document hash. So params[:financial_id] won't work. Instead you need to use params[:document][:financial_id]

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