Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

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

I have setup this HABTM relationship in the past and it has worked before....Now it isn't and I'm at my wits end trying to figure out what's wrong. I've looked through the rails guides all day and can't 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 didn't off 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to include the interests table.

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

You had it right in your post, but you didn't pluralize interests.

Update

Because this answer is still getting attention, I thought it might be a good idea to update it using ActiveRecord::Relation syntax since the above way is going to be deprecated.

@events = Event.includes(:interests).where(interests: { id: 4 })

or

@events = Event.includes(:interests).where('interests.id' => 4)

And in case you want a custom condition

@events = Event.includes(:interests).where('interests.id >= 4')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...