2013-12-13 60 views
0

這是一個棘手的問題。我有以下型號:使用accept_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 

現在,讓我們說別人已經擁有的帳戶作爲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: '[email protected]', 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: '[email protected]', 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 

但無論怎樣,我們嘗試(掛機後之前,試圖修改嵌套屬性的人的模型,update_only和reject_if在accepts_nested_attributes_for),我們不能似乎得到這在模型中工作)

我們真正需要做的是完全繞過accept_nested_attributes_for記錄創建,如果該User類型的用戶的當前帳戶存在,但如果我們放入一個reject_if,那麼它會停止創建父記錄(即專業)完全。

任何想法,我們如何能做到這一點

+0

一個評論 - 呼籲建立之前,我們知道我們可以做到這一切在控制器,但由於這是數據驅動,我們希望完全在模型中處理它。 – JoshL

回答

-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 
+0

由於專業人員和用戶模型屬性完全不同,因此在這種情況下沒有STI不起作用。此外,這不會幫助回答這個問題,除非你暗示用戶模型篡奪了我們不想做的賬戶模型。 – JoshL