简体   繁体   中英

Rails use Boolean similar to counter_cache?

A Miniatures model has many Collections. Users can have and vote for the best Collection version of a Miniature. The votes are in a model called Imagevotes which update a counter_cache attribute in the Collections model.

What I want to do is flag Collections which are ranked first for a Miniature as GOLD, then rank the 2nd, 3rd and 4th as SILVER. I realise I can do this on the Miniature model by selecting the @miniature.collection.first, but I would like to be able to store that like you would store the vote-count in a counter_cache so that I could display the total number of GOLDS or SILVERS for any one user.

Is there a way that each model could have Boolean fields called GOLD and SILVER which would be updated as new votes are cast in the same way that a counter_cache is updated?

Any pointers and further reading much appreciated.

Update:

It occurs to me that this could also be done with a sort of second index column. A vote_position column if you will, that updated with a number from "1" for the record with the highest counter_cache number and ascended from there. Then I could use @miniature.collection.where(:vote_position => "1") or similar. Perhaps this is more ideal?

As it seems for me you just need to implement method in Miniature model:

def set_gold_and_silver
  top_collections = self.collections.order("imagevotes_count desc").limit(4)
  gold = top_collections.shift 
  gold.update_attribute :is_gold, true if gold
  top_collections.each {|s| s.update_attribute :is_silver, true}
end

after that you can add it to after_create filter of Imagevotes model:

class Imagevotes < ActiveRecord::Base
  after_create :set_gold_and_silver

  def set_gold_and_silver
    self.miniature.set_gold_and_silver
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM