Sorting by a virtual attribute in Rails 3

前端 未结 2 1756
醉话见心
醉话见心 2021-02-06 18:04

BACKGROUND: I have a set of Posts that can be voted on. I\'d like to sort Posts according to their \"vote score\" which is determined by the following equation:

2条回答
  •  轮回少年
    2021-02-06 18:58

    1. You shouldn't use sort! if you are going to assign to the same variable (it is wrong in this case), you should change the sort to:

      @posts.sort!{|a, b| vote_score(b) <=> vote_score(a) }
      
    2. It looks like you are counting the votes for Post each time you call another Post which is hitting the database quite a bit and probably the source of the toll on your load times, you can use a counter_cache to count each time a vote is made and store that in the posts table. This will make it so you only do one db query to load from the posts table.

    http://guides.rubyonrails.org/association_basics.html

提交回复
热议问题