Use ActiveRecord to Find Result of 5 Nested Tables
-
25-09-2019 - |
Question
I have a User Model(:name, :password, :email), and Event model(:name, :etc) and Interest model (:name)
Then I created two join tables -> UsersInterests and EventsInterests; each not containing a primary key and only comprised of the user_id/interest_id and event_id/interest_id respectively.
I'm trying to use ActiveRecord to query a list all the events where the interest.id of EventsInterests= interest.id of UsersInterests
I'm using has_many and belongs_to relationships with the Nested Loop Plugin
My models look like so =>
user.rb
has_many :users_interests
has_many :interests, :through => :users_interests
event.rb
has_many :events_interests
has_many :interests, :through => :events_interests
interest.rb
belongs_to :users , :through => :users_interests
belongs_to :events , :through => :events_interests
users_interests.rb
belongs_to :users
belongs_to :interests
events_interests.rb
belongs_to :interests
belongs_to :events
If the @user= User.find(1), How would I query the events a user would be interested in?
I came up with this => @events.find(:all, :conditions => EventsInterests.interest_id = UsersInterests.interest_id) ??
but I get the error
undefined method `interest_id' for UsersInterests(user_id: integer, interest_id: integer):Class
umm..wtf? any help guys....I've been at this for like 4 days
Solution
First, hop into the console and make sure all of your relationships work:
User.first.events
User.first.interests
Events.first.users
Interests.first.users
Interests.first.events
# ... and so
Just to clarify, a User lists his Interests, and you want to get a list of the Events matching those interests?
User.first.interests.collect { |interest| interest.events }.uniq
Not particular efficient, but effective and easy to comprehend.
You could use User.first.interests_singular_ids
to get the ids and pass that to a find() with interest_id IN(...)
that list, too. I'm not sure how much faster it would be, though.