Ruby on rails 使用接受\u嵌套\u属性\u将嵌套多态记录迁移到新关系

Ruby on rails 使用接受\u嵌套\u属性\u将嵌套多态记录迁移到新关系,ruby-on-rails,devise,models,nested-attributes,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 :

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

 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
但是无论我们尝试什么(在挂钩之前和之后,尝试修改person模型中的嵌套属性,仅更新和拒绝,如果在accepts_nested_attributes_for上),我们似乎都无法在模型中实现这一点)

我们真正需要做的是,如果用户类型的人员的当前帐户存在,则完全绕过accepts_nested_attributes_创建记录,但如果我们输入reject_,则会完全停止父记录(即Professional)的创建


关于如何实现这一点的任何想法

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

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
class Professionaltrue
私有的
def分配现有账户(如果存在)
account\u to\u assign=帐户。通过电子邮件查找(self.account\u电子邮件)
self.account=如果account\u to\u assign.present存在,则account\u to\u assign?
结束
结束

1条评论-我们知道,在调用create之前,我们可以在controller中完成这一切,但由于这是数据驱动的,我们希望完全在模型中处理。在这种情况下,任何STI都不起作用,因为Professional和User model属性完全不同。此外,这也无助于回答这个问题,除非你暗示用户模型篡夺了账户模型,而我们并不打算这么做。
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