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
如何为 Customer
模型添加到 Agents
?
这是否是最佳方式?
Customer.find(1).agents.create(customer_id: 1, house_id: 1)
在控制台中,上述方法可以正常工作。但是我不知道如何在实际应用程序中实现。
假设一个表单被填写了,该表单需要输入 house_id
。那么我在我的控制器中要这样做吗?
def create
@customer = Customer.new(params[:customer])
@customer.agents.create(customer_id: @customer.id, house_id: params[:house_id])
@customer.save
end
总的来说,我不清楚如何在has_many :through
表中添加记录?