如何将记录添加到has_many:通过rails中的关联

时间:2011-09-04 04:01:32

标签: ruby-on-rails activerecord has-many-through

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

如何添加Agents的{​​{1}}模型?

这是最好的方式吗?

Customer

上面的工作正常从控制台,但我不知道如何在实际应用程序中实现这一点。

想象一下,客户填写的表格也以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 表中添加记录感到困惑?

3 个答案:

答案 0 :(得分:144)

我认为你可以这样做:

 @cust = Customer.new(params[:customer])
 @cust.houses << House.find(params[:house_id])

或为客户创建新房子时:

 @cust = Customer.new(params[:customer])
 @cust.houses.create(params[:house])

您还可以通过ID添加:

@cust.house_ids << House.find(params[:house_id])

答案 1 :(得分:72)

'最佳方式'取决于您的需求和最舒适的方式。混淆来自ActiveRecord对newcreate方法以及<<运算符的行为的差异。

new方法

new不会为您添加关联记录。您必须自己构建HouseAgent记录:

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

请注意,@cust.houses.newHouse.new实际上是相同的,因为您需要在两种情况下都创建Agent记录。

<<运算符

正如Mischa所提到的,您还可以在集合中使用<<运算符。这只会为您构建Agent模型,您必须构建House模型:

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

create方法

create会为您构建HouseAgent条记录,但如果您打算将其返回到您的视图或api,则需要找到Agent模型:

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

最后请注意,如果您希望在创建house时引发异常,请改用bang运算符(例如new!create!)。

答案 2 :(得分:5)

添加关联的另一种方法是使用外键列:

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

或者使用确切的列名称,传递相关记录的ID而不是记录。

agent.house_id = house.id
agent.customer_id = customer.id
相关问题