如何将记录添加到 has_many :通过 rails 中的关联 [英] how to add records to has_many :through association in rails

查看:13
本文介绍了如何将记录添加到 has_many :通过 rails 中的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 模型?

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 
  @customer = Customer.new(params[:customer])
  @customer.agents.create(customer_id: @customer.id, house_id: params[:house_id])
  @customer.save
end

总的来说,我对如何在 has_many :through 表中添加记录感到困惑?

Overall I'm confused as to how to add records in the has_many :through table?

推荐答案

我认为你可以简单地这样做:

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

您也可以通过 id 添加:

You can also add via ids:

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

这篇关于如何将记录添加到 has_many :通过 rails 中的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆