Order (has_many :order_lines)
OrderLine (belongs_to :order)
I would like to come up with a find for the Order model that only gives
me
orders that have at least one order line. Orders with no lines would be
excluded.
Can someone give me a tip as to the best way to phrase that to
ActiveRecord?
Just use the normal find method with :joins => “inner join
order_lines”. Inner join only gives you the rows that have a(t least
one) matching row in the joined table.
All in all, I’d recommend doing the screening in the db end.
def self.find_all_with_lines
find :all, :joins => “inner join order_lines on orders.id =
order_lines.order_id”
end
Note that the orders will be returned read_only by default. However,
that is less of a problem that you might think, since you rarely edit
objects in the same action where you fetch them. You can also
override this behaviour by passing the find method :readonly => false.
//jarkko
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.