首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用accepts_nested_attributes_for将嵌套的多态记录迁移到新关系

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

Stack Overflow用户
提问于 2013-12-14 01:02:36
回答 1查看 115关注 0票数 0

这是一个困难的问题。我有以下模型:

代码语言:javascript
运行
复制
 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.我们想要说的是,“如果这个人已经有一个用户帐户,那么专业记录并迁移他们的用户帐户,使其与专业帐户相关联。”

因此,用规范的术语来说:

代码语言:javascript
运行
复制
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

但是无论我们尝试什么(之前,在钩子之后,尝试修改person模型中的嵌套属性,accepts_nested_attributes_for上的update_only和reject_if ),我们似乎都不能让它在模型中工作。

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

有什么想法可以让我们做到这一点吗?

EN

回答 1

Stack Overflow用户

发布于 2013-12-14 04:00:33

已为您更新解决方案以使用现有模型结构:

代码语言:javascript
运行
复制
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
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20572007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档