在关联模型中出现问题,我无法在rails控制台中创建模型对象

时间:2015-11-09 22:47:41

标签: ruby-on-rails ruby

我正在尝试在rails控制台对象中创建但我无法使用关联

所以我有三个模型UserEventParticipant

class User < ActiveRecord::Base
  has_many :events
  has_many :participants
  has_many :events, through: :participants
end

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :participants
  has_many :user, through: :participants
end

class Participant < ActiveRecord::Base
  belongs_to :user
  belongs_to :event
end

我的工厂

FactoryGirl.define do
  factory :event do
    user
  end
end 

FactoryGirl.define do
  factory :participant do
    user
    event
  end
end

当我运行event = FactoryGirl.build(:event)时,我收到以下错误

NoMethodError: undefined method `each' for #<User:0x007f95cae313d8>
    from /Users/german/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/activemodel-4.2.3/lib/active_model/attribute_methods.rb:433:in `method_missing'...

我认为模型中的关联是关于从用户移除has_many :events而从活动和工作移除belongs_to :user但是,我想知道为什么?

1 个答案:

答案 0 :(得分:1)

您的Event类和User之间的关系有点偏。它应该是has_many :users而不是:user

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :participants
  has_many :users, through: :participants
end