Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two parameters for Rails3 scope

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
like image 567
There Are Four Lights Avatar asked Aug 10 '26 12:08

There Are Four Lights


1 Answers

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.)

like image 111
David Sulc Avatar answered Aug 13 '26 02:08

David Sulc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!