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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…