UPDATE 2:
This looks much better:
Comp.includes(:members).where('members.member_email = ? OR comps.user_id = ?', current_user.email,current_user.id)
UPDATE:
This seems to work but is there a more elegant way to do this in Rails? I feel like there must be.
@my_comps = Comp.joins('LEFT OUTER JOIN teams ON teams.comp_id = comps.id LEFT OUTER JOIN members ON members.team_id = teams.id').where('members.member_email = ? OR comps.user_id = ?', current_user.email,current_user.id).group('comps.id')
ORIGINAL:
My model associations are:
Comp.rb
has_many :teams
has_many :members, :through => :teams
Team.rb
belongs_to :comp
has_many :members
Member.rb
belongs_to :team
I want to write a query that finds all of the Comps where comps.user_id equals a particular value OR members.member_email equals a particular value for any of the members of that Comp.
I unsuccessfully tried this:
@my_comps = Comp.joins(:members).where('members.member_email = ? OR comps.user_id = ?', email, id)
There are 2 issues with the results returned: 1) it returns duplicate Comps where member_email is equal to the condition and 2) it does NOT return the Comps where the user_id is equal to the condition. I solved problem 1 by adding .group(‘id’) to the end of this code but I feel like there is likely a better way to do it, and more importantly it doesn’t solve problem 2.
Any advice on how to approach this differently? Thanks so much.
changed the suggestion, didn’t know that
.joinonly uses “INNER JOIN” in newer Rails (having an old version).The final suggestions was: use
.includeinstead of.join