Deekor
Deekor

Reputation: 9499

rails scope based on models parent attribute

I'm looking for a way to write a Rails scope to find all line_items where their account is_active = true

Something like

LineItem.should_display

Upvotes: 4

Views: 1923

Answers (1)

John
John

Reputation: 10069

EDIT

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

This produces the same result as adding the following class method in your LineItem model.

def self.should_display
  joins(:account).where(accounts: {is_active: true})
end

I think you can find more information in the Rails guides for Active Record Querying: http://guides.rubyonrails.org/active_record_querying.html

Upvotes: 7

Related Questions