这是一个困难的问题。我有以下模型:
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但是无论我们尝试什么(之前,在钩子之后,尝试修改person模型中的嵌套属性,accepts_nested_attributes_for上的update_only和reject_if ),我们似乎都不能让它在模型中工作。
我们真正需要做的是,如果存在User类型的person的当前帐户,则完全绕过accepts_nested_attributes_for记录的创建,但是如果我们放入一个reject_if,那么它将完全停止创建父记录(即专业记录)。
有什么想法可以让我们做到这一点吗?
发布于 2013-12-14 04:00:33
已为您更新解决方案以使用现有模型结构:
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
endhttps://stackoverflow.com/questions/20572007
复制相似问题