ruby-on-railsactiverecordhas-many-through

how to add records to has_many :through association in rails


class Agents << ActiveRecord::Base
  belongs_to :customer
  belongs_to :house
end

class Customer << ActiveRecord::Base
  has_many :agents
  has_many :houses, through: :agents
end

class House << ActiveRecord::Base
  has_many :agents
  has_many :customers, through: :agents
end

How do I add to the Agents model for Customer?

Is this the best way?

Customer.find(1).agents.create(customer_id: 1, house_id: 1)

The above works fine from the console however, I don't know how to achieve this in the actual application.

Imagine a form is filled for the customer that also takes house_id as input. Then do I do the following in my controller?

def create 
  @customer = Customer.new(params[:customer])
  @customer.agents.create(customer_id: @customer.id, house_id: params[:house_id])
  @customer.save
end

Overall I'm confused as to how to add records in the has_many :through table?


Solution

  • I think you can simply do this:

     @cust = Customer.new(params[:customer])
     @cust.houses << House.find(params[:house_id])
    

    Or when creating a new house for a customer:

     @cust = Customer.new(params[:customer])
     @cust.houses.create(params[:house])
    

    You can also add via ids:

    @cust.house_ids << House.find(params[:house_id])