Rick
Rick

Reputation: 1073

Strong params for has_many :through - Rails-API

I am using rails as an API service for an ember app (might not be the right approach but bear with me). I am struggling to get my head around the strong params for my main model.

My models are:

class LoanApplication < ActiveRecord::Base
# Relationships
  has_many :entity_application_links
  has_many :entities, through: :entity_application_links

# Nested attributes_for
  accepts_nested_attributes_for :entity_application_links, :entities
end

class EntityApplicationLink < ActiveRecord::Base
# Relationships
  belongs_to :entity
  belongs_to :loan_application
end

class Entity < ActiveRecord::Base
  # Relationships
  has_many :entity_application_links
end

My LoanApplicationController strong params:

def loan_application_params
  params.require(:loan_application).permit(
    :title,
    :application_state_id,
    :custom_data,
    :user_id,
    entity_application_links: [
      :id,
      :loan_application_id,
      :entity_id,
      entity: [:name]
    ]
  )
end

to test this I am sending the following data to LoanApplicationController#create:

def create
  @loan_application.user = current_user

  if @loan_application.save
    render json: @loan_application, status: :created
  else
    render json: @loan_application.errors, status: :unprocessable_entity
  end
end

Data:

{
    :title=>"Jeanie Deckow",
    :entity_application_links=>[
        {
            :entity=>{:name=>"entity1"}
        }
    ]
}

I have tried a large number of variations on my test data and the strong params but it never quite seems to work.

With the current configuration I am getting EntityApplicationLink(#69859611738960) expected, got ActionController::Parameters(#69859594766540) which I take to mean that it is expecting an instance of EntityApplicationLink but I am passing params. doing some research I have seen that I should be using entity_application_links_attributes instead but that seems to expect a loan_application_id which I do not have in the create method.

Also I believe this is going against the ember method of creating data but I have not started on that yet.

I believe I am on the right path but something does not add up and it has cost me too much time already.

I am still working on this so if you need more info let me know.

Upvotes: 0

Views: 195

Answers (1)

Gordon Isnor
Gordon Isnor

Reputation: 2105

Seems like there may be something missing in your example code?

I assume that at some point before your create action –– maybe in a before filter –– you are setting up an instance of loan application?

At any rate, I think that you'll want your strong params set up to use entity_application_links_attributes rather than entity_application_links, otherwise active record will be expecting instances of entity application links to be passed in.

Upvotes: 1

Related Questions