I have a User model, an Event Model, an Event Priority Model and a Event Type Model. Model code as follows:
class Event < ActiveRecord::Base
belongs_to :user
belongs_to :event_priority
belongs_to :event_type
attr_accessible :name, :raised_date, :location, :description, :longtitude, :latitude
attr_protected :raised_user_id, :event_priority_id, :event_type_id
end
class EventPriority < ActiveRecord::Base
has_many :events
has_many :users, :through => :events
has_many :event_types, :through => :events
end
class EventType < ActiveRecord::Base
has_many :events
has_many :users, :through => :events
has_many :event_priorities, :through => :events
end
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :first_name, :last_name, :full_name, :password, password_confirmation
has_many :events, :foreign_key => "raised_user_id", :dependent => :destroy
has_many :event_priorities, :through => :events
has_many :event_types, :through => :events
end
Can anyone explain the inability to get from the Event back to the User in the following rails console example?
irb(main):027:0> @user = User.find(2)
=> Returns the user with an ID of 2.
irb(main):028:0> @user.events
=> Returns all events for that user.
irb(main):029:0> @user.events.first.user
=> nil --HUH????
irb(main):031:0> @event = @user.events.first
=> Saves and returns the first event created by the user.
irb(main):032:0> @event.user
=> nil --Again, WHY??
irb(main):033:0> @events = Event.all
=> Saves and returns all events.
irb(main):035:0> @events.first.user
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.first
from (irb):35
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activemodel-3.0.
6/lib/active_model/attribute_methods.rb:279 -- AGAIN, WHY?
Do you have a good reason for not just using
user_idas the foreign key in theeventstable? (that’s what is causing your problem)Try adding the
foreign_keyoption in the Event class as well