Reputation: 2351
I spent a lot of time today trying to figure out how to query a many to many table for records from one of the tables it belongs to.
If I have a members table that joins users and events, what kind of query would find all of the users attending a given event, or all of the events that a given user is attending?
I ultimately came across something like this (which works):
User.joins(:members).where("members.event_id = ?", @event.id)
But can this kind of query be done without the SQL syntax? Something like:
Member.where(user: @user).first.events
Upvotes: 0
Views: 307
Reputation: 1165
You should be able to access user's events and event's users like this:
@event.users
@user.events
if you define The has_many :through association (http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association)
class User < ApplicationRecord
has_many :members
has_many :events, through: :members
end
class Member < ApplicationRecord
belongs_to :user
belongs_to :event
end
class Event < ApplicationRecord
has_many :members
has_many :users, through: :members
end
Upvotes: 1