轨道:按子模型的属性限定父模型的范围



我很难在 Rails 中弄清楚一些东西。这可能与我对SQL的了解非常有限有关,因为我非常了解Rails。我正在使用 Rails 5。

我有两种模式:申请人和申请。

class Applicant < ApplicationRecord
has_one :application
has_many :skills
accepts_nested_attributes_for :application
accepts_nested_attributes_for :skills, 
reject_if: ->(skill) { skill[:name].empty? || skill[:experience].empty? }
validates_with ApplicantValidator
end
class Application < ApplicationRecord
belongs_to :applicant
has_many :notes
VALID_STATUSES = ["in review", "accepted", "declined", "closed"]
validates_length_of   :why_interested, minimum: 25
validates             :accept_terms, acceptance: true
validates             :status, inclusion: { in: VALID_STATUSES }
before_validation :set_status
private
def set_status
self.status ||= "in review"
end
end

我想向申请人模型添加一个范围,:active,该模型仅返回具有状态为"正在审核"的应用程序的申请人。但是,我找不到在作用域内访问应用程序的方法。

我见过其他建议,用于与孩子有has_many关系的情况,但它们在我的案例中不起作用。

我怀疑这有什么不同,但我正在使用Postgres。我最接近的解决方案是添加它,但是当我运行 RSpec 时,它说应用程序表需要一个 FROM 子句。我不知道该怎么做。

scope :active, -> { joins(:application).where('"application"."status" = "in review"') }
scope :in_review_applicants, -> { joins(:application).where('application.status = ?', :in_review) }

我认为是这样的..

最新更新