Rails - HABTM Relationship -- How Can I Find A Record Based On An Attribute Of The Associated Model

Posted by ChrisWesAllen on Stack Overflow See other posts from Stack Overflow or by ChrisWesAllen
Published on 2011-01-14T00:47:59Z Indexed on 2011/01/14 0:53 UTC
Read the original article Hit count: 141

I have setup this HABTM relationship in the past and its worked before....Now it isnt and I'm at my wits end trying to figure out whats wrong. I've looking through the rails guides all day and cant seem to figure out what I'm doing wrong, so help would really be appreciated.

I have 2 models connected through a join model and I'm trying to find records based an attribute of the associated model.

Event.rb

has_and_belongs_to_many :interests

Interest.rb

has_and_belongs_to_many :events

and a join table migration that was created like

  create_table 'events_interests', :id => false do |t|
      t.column :event_id, :integer
      t.column :interest_id, :integer
   end

I tried

 @events = Event.all(:include => :interest, :conditions => [" interest.id = ?", 4 ] )

But got the error "Association named 'interest' was not found; perhaps you misspelled it?"... which I didnt of course

I tried

  @events = Event.interests.find(:all, :conditions => [" interest.id = ?", 4 ] )

but got the error "undefined method `interests' for #Class:0x4383348"

How can I find the Events that have an interest id of 4....I'm definitely going bald from this lol

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about find