【问题标题】:Two parameters for Rails3 scopeRails3范围的两个参数
【发布时间】:2011-06-20 19:44:30
【问题描述】:

目前我有两个模型:Rate 和 Item

Rate是一种投票模式,有votesplayer_id

率 has_many :votes 投票属于_to :rate

另外,对于 Item 模型,目前我的范围如下:

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

投票对所有项目进行排序。

问题是:我需要收集按 player_id 排序的 (Item.all.pop) AND 项目 类似于:Item.all.pop(player_id)

怎么做?

更新:

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

【问题讨论】:

    标签: mysql ruby-on-rails named-scope


    【解决方案1】:

    更新:(基于帖子更新和评论说明)

    你可能想要这样的东西:

    scope :pop, order('stats.votes DESC')
    
    scope :for_player, lambda{|player| joins(:rates).where(:player_id => player.id)}
    

    那你应该可以拨打Item.for_player(@my_player).pop了。

    免责声明:我不擅长在脑海中构建活动记录查询,因此上述内容可能需要一些调整...


    (原答案)

    你可能想要这样的东西:

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

    然后,您应该能够做到Item.by_player.pop 并得到您想要的。 (您可以使用Item.by_player.pop.to_sql 在控制台中查看是否生成了预期的 SQL 查询。)

    【讨论】:

    • 嘿大卫!是的,但问题是 player_id 是 Rate 模型的一部分,而不是 Item(例如 Rate 是投票的模型,并且有 votes 和 player_id)。另外,我需要 Item.by_player(current_player.id).pop 之类的东西。有什么建议吗?
    • 你能描述一下Item和Rate之间的关系吗?
    • 是的,但是 Item(在第一行)呢? Item 和 Vote 一样吗?
    • 已更新。所以,一般来说,在控制器中,我想要这样的东西:@items = Item.all.by_player(current_user).pop
    • order(stats.votes DESC)时,搜索统计中的所有投票。但我必须范围不是所有记录,而是给定 player_id 的记录。
    猜你喜欢
    • 2012-02-19
    • 2020-05-10
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2020-09-06
    • 2014-07-04
    相关资源
    最近更新 更多