1

我有一个这样定义的用户类

class User
end

我已经将其子类化以创建一个 Owner 类并与另一个 Company 类创建了 has_one 关系

class Owner < User
  has_one :company
end

class Company
  belongs_to :owner
end

在我的用户控制器中创建新用户时,我想完成以下操作:

  1. 创建新用户
  2. 创建新公司
  3. 将用户与公司关联(作为所有者,即 company.owner_id)

我可以使用以下代码完成此操作(为简洁起见)

def create
  @user = User.new(params[:user])
  @company = Company.new(params[:company])

  if @user.save
    @company.owner_id = @user.id
    @company.save
    ...

现在,这让我觉得很难看,但我似乎无法让整个 build_asociation 过程按预期工作(是的,开发和测试中都有字段)。

我应该在这里做什么?

4

1 回答 1

0

如果你需要同时创建OwnerCompany,我建议你使用accepts_nested_attributes_forin Owner。这是代码:

class Owner < User
  has_one :company
  accepts_nested_attributes_for :company
end

然后在您的控制器中,您可以执行以下操作:

def create
  @user = User.new(params[:user]) # should it be User or Owner?
  @user.company_attributes = params[:company] # assume two separate forms for User and Company
  # if you use fields_for, however, company attributes are nested under params[:user] automatically.

  if @user.save
    # do your job here
  end
end

如需完整参考,请查看Active Record 嵌套属性和视图助手fields_for

于 2012-04-30T12:46:34.137 回答