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
问题
如何添加到代理
模式客户
?
Question
How do I add to the Agents
model for Customer
?
这是最好的方式?
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.
想象一下,一个表单填的客户也需要 house_id
作为输入。然后,我做到以下几点在我的控制器?
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
@cust = Customer.new(params[:customer])
@cust.agents.create(:customer_id=>@cust.id, :house_id=>params[:house_id])
@cust.save
end
总的来说,我很困惑,如何在的has_many添加记录:通过
表格
我觉得你可以简单地做到这一点:
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])