开发者

Improve performance on retrieving class Record Association attribute values

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:

  • @user is an instance of a User class
  • article_relationships is the method "gained" by an User Active Record Association with the Article class
  • :categor开发者_高级运维y_id is an attribute of each article_relationships (that is, a database table column of article_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_id column in the articles table. This can easily be done in a migration: add_index :articles, :user_id.


You can use eager loading using include when finding @user's object

or directly skip select

@user.article_relationships.map(&:category_id)


As the other person answered, there's no direct or recommended way to do this.

The main tip is not to loop through the results twice, map() loops through every result and calls .company_id, if you're going to loop through the results again then leave the .map off and call .company_id yourself when you need it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜