2012-03-09 45 views
0

我一直在這一段時間撞我的頭。有人請複述我。工廠女孩與屬性設置器的多態關聯錯誤

方案

我有以下型號

class House < ActiveRecord::Base 
    has_one :tenancy, :dependent => :destroy, :as => :tenant 
end 

class LeaseAgreement < ActiveRecord::Base 
    has_many :tenancies 
end 

class Tenancy < ActiveRecord::Base 
    belongs_to :tenant, :polymorphic => true 
    belongs_to :lease_agreement 

    def lease=(lease) 
    if lease.rent_amount > 10000 
     # do something here 
    else 
     # do something else here 
    end 

    self.lease_agreement = lease 
    end 
end 

我的工廠

Factory.define :lease_agreement do |l| 
    l.name "Foo" 
    l.rent_amount 5000 
end 

Factory.define :tenancy do |t| 
    t.name "Foo" 
    t.association :tenant, :factory => :house 
    t.after_build { |tenancy| tenancy.lease = Factory.create(:lease_agreement) } 
end 

也試過這種

Factory.define :tenancy do |t| 
    t.name "Foo" 
    t.association :tenant, :factory => :house 
    t.after_build { |tenancy| tenancy.lease = Factory.create(:lease_agreement, :tenant => tenancy) } 
end 

當我嘗試這種方式時,在我的規範中測試的兩種方式; @house = Factory(:house)我收到以下錯誤

NoMethodError: undefined method `rent_amount' for nil:NilClass 
from /home/kibet/.rvm/gems/ruby-1.8.7-p352/gems/activesupport-3.0.5/lib/active_support/whiny_nil.rb:48:in `method_missing' 
from /home/kibet/code/ruby/stuff/app/models/tenancy.rb:44:in `lease=' 

我該怎麼辦呢?

+0

你家的工廠在哪裏? – Nitrodist 2012-03-12 19:13:14

回答

1

它看起來像是一個操作順序問題,我認爲在它評估你的after_build掛鉤之前,lease被設置爲nil,其中lease是一個合法的LeaseAgreement實例。

您的代碼無法處理正在傳入的無租約,如果您想清除關聯,則這是合法的值。嘗試處理無像這樣:

class Tenancy < ActiveRecord::Base 
    belongs_to :tenant, :polymorphic => true 
    belongs_to :lease_agreement 

    def lease=(lease) 
    if lease.present? && lease.rent_amount > 10000 
     # do something here 
    else 
     # do something else here 
    end 

    self.lease_agreement = lease 
    end 
end 

書面總是會產生一個錯誤,在通過了零租借我認爲,如果你寫你的工廠這樣的代碼

+0

感謝您抽出時間@Winfield。你的建議使它工作,我已經採取了你的建議,但我仍然想知道爲什麼我的工廠不工作。 – 2012-03-14 11:36:33

0

Factory.define :tenancy do |t| 
    t.name "Foo" 
    t.association :tenant, :factory => :house 
    t.after_build { |tenancy| tenancy.lease = Factory.create(:lease_agreement) } 
end 

你的:lease_agreement將被正確創建,它應該工作。對於lease_agreement沒有tenancy

+0

這沒有奏效,我已經嘗試過了(看起來像在這種情況下合乎邏輯的事情),但很有趣,它沒有奏效。得到了同樣的錯誤。 – 2012-03-14 11:34:22