简体   繁体   中英

Rails active record query through multiple tables

I am trying to query for questions based on subject or category. I have a Category model which has many Subjects, and a Subjects model which has many Questions. How do I select 50 questions where the subject_id = x or category_id = y? I'm not sure if I need to change my model associations then query or use a query with the current associations. Here are the models (stripped of some excess code):

category.rb

class Category < ActiveRecord::Base
  has_many :subjects, class_name: "Subject",
                      foreign_key: "category_id"
  has_many :questions, through: :subjects
end

subject.rb

class Subject < ActiveRecord::Base
  belongs_to :category  
  has_many :questions, class_name: "Question",
                       foreign_key: "subject_id"
end

question.rb

class Question < ActiveRecord::Base
  belongs_to :subject
end

The most success I've had is with "Question.joins(:subject).group(category_id:1)", which only returns the last question with an associated category. Any suggestions? Thanks!

So you could make a scope

class Question < ActiveRecord::Base

  scope :q_or_c ->(q, c){ where('category_id = ? OR question_id = ?', q, c) }

  ...

end

and then call it with

Question.q_or_c(question_id, category_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM