Keep the Queries Down or "Referencing eagerly loaded models"

Before I start, I’ve read the ActiveRecord docs on eager loading, but
for the life of me, I can’t seem to get it working.

What I mean by this, is that the eager query looks good (I can paste the
sql dump, but it looks good to me - and runs well independantly), but it
seems that I’m referencing the eagerly loaded data in a way that
activerecord doesn’t understand (my assumption) - thus I’m getting a
tonne of extra queries.

[first, the domain:
WorkOrders has_many: WorkOrderItems
WorkOrderItems belongs_to :WorkOrder
WorkOrderItems belongs_to :ProductsAndServices

secondly, the controller looks like:
@work_order = WorkOrder.find(params[:id])
@work_order_items = @work_order.WorkOrderItems.find(:all, :include
=> [:WorkOrder, :ProductsAndServices ] )

(you’ll note that I’m eagerly loading the work_order from the
work_order_item - that’s because the WorkOrderItem model references its
work_order for some processing - see “pst” below)

And in the view, I reference as such:

@work_order_items.each {|item| <<
Hash[“Part #”, item.ProductsAndServices.part_number,“Description”,
item.description, “Quantity”,item.quantity, “Price”,
number_to_currency(item.price), “Extended”,

The above generates @work_order_items.count queries to the
ProductsAndServices table. Why is that? Do I reference the eagerly
loaded data incorrectly?

With the same symptom, further down in the same view I make a call to a
WorkOrderItems method “pst” - this method references both eagerly
referenced models - WorkOrders and ProductsAndServices using the syntax:

#calculate the line item pst
def pst
if (self.WorkOrder.charge_pst? and
sub_total * 0.07

Again, I see that database queries are made to retrieve both WorkOrder
and ProductsAndServices.

Probably the same problem on my part. Any ideas ninjas?

Thanx for any help.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs