通过联合表进行一对多的Rails

时间:2013-05-08 12:06:07

标签: ruby-on-rails-3 one-to-many

我最近的项目中有以下模型:

class User < ActiveRecord::Base
  # setup association
  has_one :user_detail
  has_one :employee
  has_one :company, :through => :employee
end

class Employee < ActiveRecord::Base
  belongs_to :user
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :employees
  has_many :users, :through => :employees
end

要为用户注册构建嵌套表单,我需要在User#new action中构建公司,但是,我尝试使用代码但不工作。

def new
  @user = User.new()
  @company = @user.build_company()
end

错误显示@user没有build_company方法。

所以我尝试了另一种方法:

def new
  @user = User.new()
  @company = @user.company.build()
end

仍然无法正常工作。错误显示build()不是nil类的方法。

rails不支持这种一对多的联合表方法吗?

1 个答案:

答案 0 :(得分:0)

@company = Company.new(user: @user)

@company = @user.build_employee.build_company