German
German

Reputation: 433

Trouble in associations model, I can't create model object in rails console

I am trying to create in rails console object but I am having trouble using the associations

So I have three models User, Event, Participant

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

My factories are

FactoryGirl.define do
  factory :event do
    user
  end
end 

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

When I run event = FactoryGirl.build(:event), I get the following error

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'...

I think so is about associations in the model I remove has_many :events from User and belongs_to :user from event and work but, I want to know why?

Upvotes: 1

Views: 223

Answers (1)

max
max

Reputation: 102250

The relation between your Event class and User is a bit off. it should be has_many :users not :user.

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

Upvotes: 1

Related Questions