gpt4 book ai didi

mysql - Rails3 作用域的两个参数

转载 作者:可可西里 更新时间:2023-11-01 08:37:41 26 4
gpt4 key购买 nike

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

Rate是投票的模型,有votesplayer_id

评分 has_many :votes投票给 belongs_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

最佳答案

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

你可能想要这样的东西:

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 查询。)

关于mysql - Rails3 作用域的两个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6416566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com