Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Grabbing IDs instead of hydrating a model object (See related posts)

Sometimes you just want the IDs of a set of objects instead of creating a bunch of model objects. It turns out this is easy to do.

For example, if we want to get back a list of tag ids in our Product model to do some processing/munging:

def tag_ids
    sql = "SELECT tag_id FROM products_tags WHERE product_id = #{self.id} ORDER BY tag_id ASC"
    ActiveRecord::Base.connection.select_values(sql).collect! { |x| x.to_i }
end


Voila, an array of integers. Much faster, depending on the size of your model object.

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts