【问题标题】:Mongoid has_many association and factorygirlMongoid has_many 关联和 factorygirl
【发布时间】:2012-07-17 07:21:25
【问题描述】:

我是第一次使用 mongoid,但在工厂中为我的规范创建 has_many 关联时遇到问题。

场景是这样的:

我有一个小组课:

class Group
  include Mongoid::Document
  field :name, :type => String
end

我有一个运动课。一个练习可以属于许多组。练习类目前是这样定义的:

class Exercise
  include Mongoid::Document
  field :name, :type => String
  field :description, :type => String

  has_many :groups

  validates_presence_of :name, :description
end

我想使用 factorygirl 为规格创建实例。我正在为如何做到这一点而苦苦挣扎。

目前我的运动工厂是这样的;

FactoryGirl.define do
  factory :exercise do
    name "Preacher curls"
    description "Do something"

    after(:build) do |exercise|
      exercise.groups << FactoryGirl.build(:group)
    end
  end
end

这会导致以下错误:

 NoMethodError:
   undefined method `=' for #<Group _id: 4fbc6f5a26a3181742000004, _type: nil, name: "Arms">

如何正确创建运动工厂以添加 group_ids?

【问题讨论】:

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


    【解决方案1】:

    尝试添加

    belongs_to :exercise
    

    进入你的 Group 类

    应该是这样的:

    class Group
      include Mongoid::Document
      field :name, :type => String
      belongs_to :exercise
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多