2014-03-27 88 views
0

我想根據主題或類別查詢問題。我有一個包含很多主題的分類模型和一個有許多問題的主題模型。如何選擇subject_id = x或category_id = y的50個問題?我不確定是否需要更改我的模型關聯,然後查詢或使用當前關聯的查詢。下面是模型(剝離了一些多餘的代碼):通過多個表的Rails活動記錄查詢

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 

最成功的我'had been with with「Question.joins(:subject).group(category_id:1)」,它只返回帶有關聯類別的最後一個問題RY。有什麼建議麼?謝謝!

+0

調用它,我想我有一個在這裏給定類別的權利查詢:Question.joins(:主題).merge (Subject.where(:category_id => 1)),現在選擇50個隨機問題。 。 。 – user3291025

回答

0

所以,你可以做一個範圍

class Question < ActiveRecord::Base 

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

    ... 

end 

,然後用

Question.q_or_c(question_id, category_id)