Wednesday, November 02, 2011

ActiveRecord::Relation, undefined method error

If you are using the active record relationships to access columns, for instance:

Article has many comments
article.comments.where("spam = ?", false).order("created_at asc")

This returns ActiveRelation object that does not fire the query. Only when you loop through the results you can access the columns of comments objects. If you want to force the call to the database just append "all" to it like this:

article.comments.where("spam = ?", false).order("created_at asc").all