从 activerecord 中获取所有字段,按不同 table 中的列过滤

Get all fields from activerecord, filtered by a column in a different table

这是一个简单的问题,但由于我是 sql 和 Rails 的新手,所以我找不到答案。 假设我有一个竞赛模型,每个竞赛都有很多问题。 即比赛 has_many 问题。问题属于竞赛

比赛有一个列 "status",可能的值为 "open" 和 "closed"

我想向仍在"open"

的用户(无论他们属于哪个比赛)显示所有问题

我正在寻找这样的东西,但这在语法上不正确。 Question.where(competition.status="open")

这是您想要的查询:

Question.joins(:competition).where('competitions.status = ?', 'open')

但是你最好在你的 QuestionModel 中使用这个方法,比如

class Question < ActiveRecord::Base

  def self.from_opened_competitions
    joins(:competition).where('competitions.status = ?', 'open')
  end

end