使用accepts_nested_attributes_for将嵌套的多态记录迁移到新关系

时间:2013-12-13 17:02:36

标签: ruby-on-rails devise models nested-attributes

这是一个艰难的。我有以下型号:

 class Account < ActiveRecord::Base
    belongs_to :accountable, :polymorphic => true

 class Professional < ActiveRecord::Base
    has_one :account, as: :accountable, dependent: :destroy
    accepts_nested_attributes_for :account, :allow_destroy => true

 class User < ActiveRecord::Base
    has_one :account, as: :accountable, dependent: :destroy
    accepts_nested_attributes_for :account, :allow_destroy => true

现在,我们可以说有人已经拥有User帐号,但他们会注册为Professional.我们想要基本上说“如果此人尝试注册已经拥有用户帐户,那么专业记录和迁移他们的用户帐户以与专业帐户相关联。“

所以在规范方面:

describe "A person with an existing user account for their email address", focus: true do
  before(:each) do
    @user = create(:user, account_attributes: {email: 'testdesigner@test.com', password: 'testing', password_confirmation: 'testing'})
  end

  it "can still sign up as a professional with the same email address" do
    # need to transfer the user account to the professional and delete it
    pro = Professional.new(first_name: 'Test', last_name: 'Designer', company_name: 'A Design Firm', account_attributes: {email: 'testdesigner@test.com', password: 'testing', password_confirmation: 'testing'})

    pro.save.should be_true

    account = Account.find_by_email(@user.email)
    account.accountable_type.should eql 'Professional'

    pro.account.should eql account
  end
end

但无论我们尝试什么(在钩子之前,尝试修改人员模型中的嵌套属性,在accepts_nested_attributes_for上更新update_only和reject_if),我们似乎无法在模型中使用它)

我们真正需要做的是完全绕过accepts_nested_attributes_for记录创建,如果存在User类型的当前帐户,但是如果我们输入reject_if则它将完全停止创建父记录(即Professional)。

我们如何才能实现这一目标

1 个答案:

答案 0 :(得分:-1)

更新了您使用现有模型结构的解决方案:

class Professional < ActiveRecord::Base
  before_create :assign_existing_account_if_exists

  has_one  :account, as: :accountable, dependent: :destroy
  delegate :email, to: :account, prefix: true, allow_nil: true

  accepts_nested_attributes_for :account, :allow_destroy => true

  private

  def assign_existing_account_if_exists
    account_to_assign = Account.find_by_email(self.account_email)
    self.account = account_to_assign if account_to_assign.present?
  end
end