how to add records to has_many :through association in rails

五迷三道 提交于 2019-11-27 06:00:15
Mischa

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])

'The best way' depends on your needs and what feels most comfortable. Confusion comes from differences ActiveRecord's behavior of the new and create methods and the << operator.

The new Method

new will not add an association record for you. You have to build the House and Agent records yourself:

house = @cust.houses.new(params[:house])
house.save
agent = Agent(customer_id: @cust.id, house_id: house.id)
agent.save

Note that @cust.houses.new and House.new are effectively the same because you need to create the Agent record in both cases.

The << Operator

As Mischa mentions, you can also use the << operator on the collection. This will only build the Agent model for you, you must build the House model:

house = House.create(params[:house])
@cust.houses << house
agent = @cust.houses.find(house.id)

The create Method

create will build both House and Agent records for you, but you will need to find the Agent model if you intend to return that to your view or api:

house = @cust.houses.create(params[:house])
agent = @cust.agents.where(house: house.id).first

As a final note, if you want exceptions to be raised when creating house use the bang operators instead (e.g. new! and create!).

Another way to add associations is by using the foreign key columns:

agent = Agent.new(...)
agent.house = House.find(...)
agent.customer = Customer.find(...)
agent.save

Or use the exact column names, passing the ID of the associated record instead of the record.

agent.house_id = house.id
agent.customer_id = customer.id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!