setter和getter在FactoryGirl中使用Rails 3.2.8得到零值

时间:2012-10-26 00:48:11

标签: ruby-on-rails ruby-on-rails-3 autocomplete getter-setter

在我们的发票模型中,有两列 - customer_idcustomer_name。为了使用自动完成(JQuery),customer_name的setter和getter被添加到发票模型中:

  def customer_name
    customer.try(:name)
  end

  def customer_name=(name)
    self.customer = Customer.find_by_name(name) if name.present?
  end 

在发票模型中,有:

  belongs_to :customer

但在此之后,customer_idcustomer_name始终为nil FactoryGirl.build(:invoice)。如果从发票模型中删除了getter和setter,则FactoryGirl会将正确的值分配给customer_idcustomer_name。这是FactoryGirl:

 factory :invoice do 
.....
    customer_id             2
    customer_name           'a customer name'
...

  end

为什么customer_name的getter和setter会导致FactoryGirl中的nil

2 个答案:

答案 0 :(得分:1)

FactoryGirl.build(:invoice)实际上并不保存新实例化的对象。您可能需要使用FactoryGirl的内置回调来获取此rollin。

未经过测试

FactoryGirl.define do
  factory :customer do
    name "A customer"
  end
end

FactoryGirl.define do
  factory :invoice do
    name "An invoice"
    after_build do |invoice|
      invoice.customer = FactoryGirl.build(:customer)
    end
  end
end

一些资源......

http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl

http://icelab.com.au/articles/factorygirl-and-has-many-associations/

希望这能指出你正确的方向!

答案 1 :(得分:0)

我们所做的是为jquery自动填充添加字段customer_name_autocomplete,而不是使用customer_name这是发票表中的列。基本上我们只是解决问题而不知道导致上述问题的原因。失败的所有rspec案件再次通过。