基于模型父属性的Rails范围

Dee*_*kor 4 ruby-on-rails ruby-on-rails-4

  • 我有2个模型。line_itemaccount
  • line_item属于account
  • account有专栏is_active

我正在寻找一种编写Rails范围的方法,以查找line_items其帐户的所有位置is_active = true

就像是

LineItem.should_display
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 5

编辑

class LineItem < ActiveRecord::Base
  scope :should_display, -> { joins(:account).where(accounts: {is_active: true}) }
end
Run Code Online (Sandbox Code Playgroud)

这产生与在LineItem模型中添加以下类方法相同的结果。

def self.should_display
  joins(:account).where(accounts: {is_active: true})
end
Run Code Online (Sandbox Code Playgroud)

我想您可以在Rails的Active Record查询指南中找到更多信息:http : //guides.rubyonrails.org/active_record_querying.html