2012-03-09 47 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