3

Currently i have two models: Rate and Item

Rate is a model for voting, and there is votes and player_id

Rate has_many :votes Vote belongs_to :rate

Also, for Item model, currently i have a scope like:

scope :pop, proc { order('votes.votes DESC') }

to sort all Items by vote.

The question is: i need to collect items sorted (Item.all.pop) AND by player_id Something like: Item.all.pop(player_id)

How it could be done?

Update:

rate.rb

class Rate < ActiveRecord::Base
  belongs_to :player
  belongs_to :item
end

item.rb

class Item < ActiveRecord::Base
  has_many :rates
  scope :pop, proc { order('rates.votes DESC') }
end
There Are Four Lights
  • 1,406
  • 3
  • 19
  • 35

1 Answers1

2

UPDATE: (based on post update and comment clarifications)

You probably want something like this:

scope :pop, order('stats.votes DESC')

scope :for_player, lambda{|player| joins(:rates).where(:player_id => player.id)}

Then you should be able to call Item.for_player(@my_player).pop.

Disclaimer: I'm not great at building active record queries off the top of my head, so the above may need some tweaking...


(Original answer)

You probably want something like this:

scope :pop, order('stats.votes DESC')

scope :by_player, group('player_id')

Then, you should be able to do Item.by_player.pop and get what you want. (You can check in the console with Item.by_player.pop.to_sql to see if the expected SQL query is generated.)

David Sulc
  • 25,946
  • 3
  • 52
  • 54