2012-07-17 114 views
3

我第一次使用mongoid,並且在創建工廠中的has_many關聯時遇到了問題。Mongoid has_many association and factorygirl

的情況是這樣的:

我有一組類:

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爲specs創建實例。我正在努力如何做到這一點。

目前我的鍛鍊工廠看起來像這樣;

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?

回答

0

嘗試添加

belongs_to :exercise 

到您的組類

它應該是這樣的:

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