Note that there are some explanatory texts on larger screens.

plurals
  1. POWeird results when testing model associations in Rails Console
    primarykey
    data
    text
    <p>I have a User model, an Event Model, an Event Priority Model and a Event Type Model. Model code as follows:</p> <pre><code>class Event &lt; 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 &lt; ActiveRecord::Base has_many :events has_many :users, :through =&gt; :events has_many :event_types, :through =&gt; :events end class EventType &lt; ActiveRecord::Base has_many :events has_many :users, :through =&gt; :events has_many :event_priorities, :through =&gt; :events end class User &lt; ActiveRecord::Base attr_accessor :password attr_accessible :first_name, :last_name, :full_name, :password, password_confirmation has_many :events, :foreign_key =&gt; "raised_user_id", :dependent =&gt; :destroy has_many :event_priorities, :through =&gt; :events has_many :event_types, :through =&gt; :events end </code></pre> <p>Can anyone explain the inability to get from the Event back to the User in the following rails console example?</p> <pre><code>irb(main):027:0&gt; @user = User.find(2) =&gt; Returns the user with an ID of 2. irb(main):028:0&gt; @user.events =&gt; Returns all events for that user. irb(main):029:0&gt; @user.events.first.user =&gt; nil --HUH???? irb(main):031:0&gt; @event = @user.events.first =&gt; Saves and returns the first event created by the user. irb(main):032:0&gt; @event.user =&gt; nil --Again, WHY?? irb(main):033:0&gt; @events = Event.all =&gt; Saves and returns all events. irb(main):035:0&gt; @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? </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload