使用has_many:通过并建立 [英] using has_many :through and build

查看:66
本文介绍了使用has_many:通过并建立的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型,所有模型都具有has_many:through关系.他们看起来像这样:

i have three models, all for a has_many :through relationship. They look like this:

class Company < ActiveRecord::Base

  has_many :company_users, dependent: :destroy
  has_many :users, through: :company_users

  accepts_nested_attributes_for :company_users, :users

end

class CompanyUser < ActiveRecord::Base
  self.table_name = :companies_users #this is because this was originally a habtm relationship
  belongs_to :company
  belongs_to :user
end

class User < ActiveRecord::Base
  # this is a devise model, if that matters

  has_many :company_users, dependent: :destroy
  has_many :companies, through: :company_users

  accepts_nested_attributes_for :company_users, :companies

end

这可以很好地加载,并且联接可以很好地用于查询.但是,只要我做类似的事情

this loads fine, and the joins are built fine for queries. However, whenever i do something like

@company = Company.last
@user = @company.users.build(params[:user])

@user.save    #=> true
@company.save #=> true

记录和CompanyUser记录均被创建,但是CompanyUser记录中的company_id字段设置为NULL

both the User record and the CompanyUser records get created, but the company_id field in the CompanyUser record is set to NULL

INSERT INTO `companies_users` (`company_id`, `created_at`,`updated_at`, `user_id`) 
VALUES (NULL, '2012-02-19 02:09:04', '2012-02-19 02:09:04', 18)

当您@company.users << @user

我确定我在这里做一些愚蠢的事情,我只是不知道什么.

I'm sure that I'm doing something stupid here, I just don't know what.

推荐答案

您不能像这样使用 has_many:through ,您必须这样做:

You can't use a has_many :through like that, you have to do it like this:

@company = Company.last
@user    = User.create( params[:user] ) 
@company.company_users.create( :user_id => @user.id )

然后您将正确定义关联.

Then you will have the association defined correctly.

更新

在下面的评论中,由于您已经具有 accepts_nested_attributes_for ,因此您的参数必须像这样:

In the case of the comment below, as you already have accepts_nested_attributes_for, your parameters would have to come like this:

{ :company => 
    { :company_users_attributes => 
        [ 
          { :company_id => 1, :user_id => 1 } ,
          { :company_id => 1, :user_id => 2 },
          { :company_id => 1, :user_id => 3 } 
        ]
    } 
}

您会自动将用户添加到公司中.

And you would have users being added to companies automatically for you.

这篇关于使用has_many:通过并建立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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