如何将记录添加到HAS_MANY:通过导轨协会 [英] how to add records to has_many :through association in rails

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

问题描述

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

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

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