【发布时间】:2011-11-09 23:20:32
【问题描述】:
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 表中添加记录感到困惑?
【问题讨论】:
-
你会将函数“create”存储在哪个控制器中?
标签: ruby-on-rails activerecord has-many-through