【问题标题】:Factory Girl Association Not Working工厂女孩协会不工作
【发布时间】:2013-11-03 18:09:02
【问题描述】:

我在 FactoryGirl 中设置了一个非常简单的关联,但由于某种原因它无法正常工作。该应用程序适用于旅游公司,因此每个旅游都有一个目的地(我正在使用 ActiveRecord,所以 Tour 模型 belongs_to a Destination - 所有旅游都需要此关联)。所以我这样设置我的工厂:

# spec/factories.rb
FactoryGirl.define do

  factory :destination do
    name "Example Destination"
    city "Example City"
    state "CA"
  end

  factory :tour do
    departure_date { 1.day.from_now }
    return_date { 1.day.from_now }
    destination
  end
end

但是,当我调用FactoryGirl.attributes_for(:tour) 时,它会返回:

{:departure_date => Mon, 04 Nov 2013 17:51:26 UTC +00:00,
 :return_date    => Mon, 04 Nov 2013 17:51:26 UTC +00:00}

没有destination_id!为什么?

destination 工厂运行良好。

我尝试以旧方式 association :destination, factory: :destination 定义关联,但这并没有帮助。如果我手动将destination_id 定义为destination_id FactoryGirl.create(:destination).id,我可以让它工作,但我不应该这样做。知道为什么它不起作用吗?

【问题讨论】:

  • 如果您最初不想分配任何东西,为什么不使用destination nil
  • 我确实想指定目的地——所有tours都需要destination_id

标签: ruby-on-rails factory-bot


【解决方案1】:

attributes_for 不加载关联对象。它只会为您请求的对象生成属性。

要让它加载关联的destination,请改用buildcreate

【讨论】:

    【解决方案2】:

    attributes_for 不会创建关联属性(我相信是设计使然)。这应该有效:

    FactoryGirl.attributes_for(:tour, :destination_attributes => FactoryGirl.attributes_for(:destination))
    

    但是,这可能是一个更巧妙的解决方案:

    https://stackoverflow.com/a/10294322/632735

    :)

    【讨论】:

    • 我的tour 模型是否需要接受destination 的嵌套属性才能正常工作?因为它对我不起作用(“未知属性:destination_attributes”)。不过感谢您的链接!非常有帮助。如果你编辑答案,我会给你一个赞成票
    • 您的 Tour 模型中有 attr_accessible :destination_attributes 吗?那应该对它进行排序:)
    • 这个问题是attributes_for 没有保留记录,因此永远不会生成destination_id
    • 是的,很好,Chris 和 Nathan 专门寻找 destination_id,所以我猜 attributes_for 在这种情况下不会有太大帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多