【问题标题】:factory_girl > association with lazy attributesfactory_girl > 与惰性属性的关联
【发布时间】:2013-04-13 02:22:47
【问题描述】:

我正在尝试让工厂构建一个带有子对象Rating 的Offering 对象,该对象将从它的父对象接收item_id。

FactoryGirl.define do
  factory :offering do
    item_id nil
    element_id nil
    association :rating, factory: :rating, strategy: :build, :item => item_id
  end
end

产品是用

创建的
offering = FactoryGirl.create :offering, item_id: 21, element_id: 211

但在运行时,它会因错误而中止

Failure/Error: offering = FactoryGirl.create :offering, item_id: 21, element_id: 211
 ArgumentError:
   Trait not registered: item_id

我认为发生错误是因为关联定义中的 item_id 不是“惰性”,因此未定义。

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails activerecord factory-bot


    【解决方案1】:

    不幸的是,我不知道有任何方法可以对关联进行惰性评估(如果我在这方面有误,请有人纠正我)。您最好的选择可能是使用回调。假设您为 :rating 定义了一个工厂,请尝试替换您的

    association :rating, factory: :rating, strategy: :build, :item => item_id

    与

    after(:create) do |offering, evaluator|
      FactoryGirl.build(:rating, item_id: evaluator.item_id, element_id: evaluator.element_id)  
    end
    

    【讨论】:

      【解决方案2】:

      你可以懒惰地定义关联:

      FactoryGirl.define do
        factory :offering do
          item_id nil
          element_id nil
          rating { association(:rating, :item => item_id) }
        end
      end
      

      【讨论】:

      • @AliQanavatian 你能更具体一点吗?如何使用这个代码示例你有什么不明白的地方?
      • 可能是一个 create: 语句?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      相关资源
      最近更新 更多