I’m having trouble wrapping my head around more advanced Rails query methods. In this case, I have three tables: Users, Friendships, and Events.
I have set it up as follows in the models for each
User-> :has_many => :friendships, :has_many => :items
Friendship-> :belongs_to => :user
Event-> belongs_to => :user
Friendships are simply two columns: “user_id” and “friend_id” so each new friendship would create two new rows.
Here is the query I’m using to find “the first four events belonging to a friend of the current_user that has a start_date that is later than right now.”
find_by_sql(["SELECT DISTINCT e.id
FROM events e
WHERE e.start_date > ?
AND e.user_id IN(
SELECT f.user_id
FROM friendships f
WHERE f.friend_id = ?)
LIMIT 0,4", Time.zone.now,current_user.id])
What is the true and elegant way to do something like this in Rails? I have a feeling this is also extremely inefficient…
You should be able to use
:joinand:conditionsI haven’t really done a whole lot of complex querying like this, but I pieced this together from the examples here: http://guides.rubyonrails.org/active_record_querying.html
Edit:
You may have to add to Event:
Edit2: Looks like you’ll have to actually use a nested join:
Here is the model code that I used:
And, some example output if that may be helpful at all: