Reputation: 4203
In reports.rb, I have:
has_and_belongs_to_many :elements
In elements.rb, I have:
has_and_belongs_to_many :reports
The following method works, but it seems longer than it should be:
@elements = []
Element.all.each do |element|
@elements << element if element.reports.empty?
end
I've tried the following, but it doesn't work as there is no reports column:
@element = Element.where(reports.empty?)
Unfortunately, all the words I've tried punching into the Rails API references — find, etc — are so generic that I can't find a method that works that way that you can see I when where
to work. Is there one? Or is there some other way I can simplify this method?
Upvotes: 0
Views: 82
Reputation: 4203
Answer turned out to be:
@elements = Element.all.keep_if {|e| e.reports.empty?}
Upvotes: 0
Reputation: 1108
I can think of one way to do this in a low-level way.
Element
.joins("LEFT OUTER JOIN element_reports")
.group("elements.id")
.having("element_reports.id IS NULL")
This at least pushes the responsibility for filtering to the DB, instead of fetching all the records. This should be a win especially if there are many records, or if they are particularly fat.
Upvotes: 1