這是一個棘手的問題。我有以下型號:使用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,那麼它會停止創建父記錄(即專業)完全。
任何想法,我們如何能做到這一點
一個評論 - 呼籲建立之前,我們知道我們可以做到這一切在控制器,但由於這是數據驅動,我們希望完全在模型中處理它。 – JoshL