我最近的项目中有以下模型:
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 操作中构建公司,但是,我尝试了以下代码但没有工作。
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 不支持这种一对多的通过联表的方式吗?