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, :pas开发者_如何学编程sword, 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_id
as the foreign key in the events
table? (that's what is causing your problem)
Try adding the foreign_key
option in the Event class as well
You can get from a User to an Event because you've told the "User has_many Events" association to use your custom foreign key. You can't get back, because you haven't told the "Event belongs_to User" association to use that custom key. It therefore expects the default key of "user_id", which it can't find, so it can't get back.
I'm surprised it handles it gracefully (by returning nil), actually - I would have expected it to throw an exception at that point.
And I'm afraid I have no idea about your second problem. I can only guess that you somehow set @events
to nil
on the missing IRB line #34...
Hope that helps!
精彩评论