I am using Ruby on Rails 3.0.7 and I would like to improve the following code:
@user.article_relationships.select(:category_id).map(&:category_id)
Where:
@useris an instance of a User classarticle_relationshipsis the method “gained” by an User Active Record Association with the Article class:category_idis an attribute of eacharticle_relationships(that is, a database table column ofarticle_relationships)
The output of the above code is something like this:
# Those are all 'category_id' values present in the 'article_relationships' array
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
There is a way to improve that code for performance purposes (mostly for the select(:category_id).map(&:category_id) part)? That is, there is a “direct” way to retrieve category_id data?
In a word… no. There’s not a more “direct” way to access the category_ids. Some notes though:
You don’t have to do
.select(:category_id). Unless article records contain lots of data, the performance increase would be negligible.@user.article_relationships.map(&:category_id)should do.More than anything, the largest performance boost you could get here is by indexing the
user_idcolumn in the articles table. This can easily be done in a migration:add_index :articles, :user_id.