Friday, May 30, 2008

active_scaffold Woes

I recently used this plugin in my current project to build the admin interface. It works great but I faced an interesting problem that i would like to share with an example.

class Order < ActiveRecord::Base
has_many :products
end

If you see the page generated using scaffolding for the Order model you will see some links to the products in one of the columns for each Order (provided you have included products as one of the attributes in the scaffolding configuration). Lets say you are not much interested in those links, you just want the count of products. You can use active record field overrides to achieve this by putting a helper method in your OrderHelper

module OrderHelper
def products_column(record)
record.products.size
end
end

For a small number of records it works well but as the number grows it becomes very slow because of the join query it makes behind the scenes and for a few thousand records it may actually hang your database server for a while.

So to avoid this, there is a simple way out, just use the virtual attributes. Create a virtual attribute for the Order model that returns the product count and include that as an attribute in the active scaffolding.

No comments: