I'm new to rails and this is the situation I'm in: I have a User model that has many tournaments, a Tournament has many users and questions and a Question belongs to a tournament. I'm trying to write a query for all questions that are in tournaments the user is a part of, for example if we have the user A in tournament 1 which has questions alpha, beta, gamma and another tournament 2 with questions omega and delta, I want to display alpha, beta and gamma. So far this is what I've come up with:def user_questions  first_questions = scope.joins(:tournament)\                         .merge(Tournament.where(id: user.tournaments.first.id))  user.tournaments.each do |tournament|    current_questions = scope.joins(:tournament)\                             .merge(Tournament.where(id: tournament.id))    first_questions = first_questions.or(current_questions)  end  first_questionsend(Imagine scope is Question) Now this works but even I can see this code isn't that good, to put it mildly. I'm looking for suggestions on how to improve it.
Rails query for all questions in tournaments that a user participates in
beginner;ruby;ruby on rails;active record;join
Ok, so based on what your said your associations are you can doclass User  has_many :tournaments  has_many :questions, through: :tournamentsendu = User.firstquestions = u.questionsIf you don't want that for some reason you can doclass User  has_many :tournamentsendclass Question  belongs_to :tournamentendu = User.firstquestions = Question.where(tournament_id: u.tournament_ids)Rails will convert that into a where tournament_id in (?) sql statement