Monday, June 16, 2008

ActiveRecord Association Weird Length Method

The method 'length' defined for ActiveRecord associations works in a very weird manner.

consider this example

class User < ActiveRecord::Base
has_many :feeds

i was using the class and writing this snippet of code to get the count of feeds in the db

@user = User.find :first

puts @user.feeds.length

looking at the log, i found that the added query was

SELECT * FROM `feeds` WHERE (feeds.user_id = 1)

and not

SELECT count(*) AS count_all FROM `feeds` WHERE (feeds.user_id = 1)

so in order to get away from such weird sql statement which will exhaust a very large bandwidth getting all records to count them, use this instead

puts @user.feeds.count


puts @user.feeds.size

but don't use 'length' method

No comments: