Rails通过多个表进行活动记录查询

时间:2014-03-27 02:26:03

标签: sql ruby-on-rails activerecord rails-activerecord

我正在尝试根据主题或类别查询问题。我有一个有很多主题的分类模型,以及一个有许多问题的主题模型。如何选择subject_id = x或category_id = y的50个问题?我不确定是否需要更改模型关联,然后查询或使用当前关联的查询。以下是模型(剥离了一些多余的代码):

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

我最成功的是“Question.joins(:subject).group(category_id:1)”,它只返回带有相关类别的最后一个问题。有什么建议?谢谢!

1 个答案:

答案 0 :(得分: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)