我一直在敲打这个。有人请给我打电话。
方案
我有以下型号
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 :(得分:1)
它看起来像是一个操作顺序问题,我认为租约在评估你的after_build挂钩之前被设置为nil,其中lease是一个合法的LeaseAgreement实例。
您的代码无法处理传入的nil租约,如果要清除关联,则这是合法值。尝试像这样处理nil:
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
写入的代码将始终产生错误并传入nil租约。
答案 1 :(得分: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
将被正确创建,它应该可以正常工作。 tenancy
没有lease_agreement
。