so i have users ,airlines and review .An airline has_many :reviews has_many :users,through: :reviews.A user has_many :reviews has_many :airlines,through: :reviews and a review belongs to an airlines and user.A user can experience multiple airlines.I dont understand a way to get all the reviews of a user of travelling by a particular airline.
here is my seed data
singapore_airlines=Airline.create(name: 'Singapore Airlines')
cathy=User.create(name:"Cathy",email:"[email protected]",admin:false)
Review.create(image:"https://worldofwanderlust.com/wp-content/uploads/2022/03/866D61D2-FFD1-4392-9596-0E4E372D18D9.jpg", date: DateTime.new(2021, 11, 1),destination:"Singapore to Tokyo",seat:"Business class",description:"If you want comforting long flights always take Singapore airlines",likes:0,dislikes:0,airline_id:singapore_airlines.id,user_id: cathy.id)
so im aware in the console i can do something like sing=Airline.find(1) and then sing.reviews.........but that will give me all the reviews of singapore airline. i want only the review given by cathy.
CodePudding user response:
To do this directly, you could do:
singapore_airlines.reviews.where(user_id: cathy.id)
Or:
cathy.reviews.where(airline_id: singapore_airlines.id)
Or:
Review.where(user_id: cathy.id, airline_id: singapore_airlines.id)
...Or if this is a common lookup, you could consider making a convenience method for it such as:
class Airline < ApplicationRecord
# ...
def reviews_for_user(user)
reviews.where(user_id: user.id)
end
# ...
end
# Usage:
singapore_airlines.reviews_for_user(cathy)