4

我需要查询帮助。我有多个食堂,每个食堂都有多个餐点,每餐都有多个 MealPicks。

虽然我不知道这个MealPick模型是不是好主意,因为我需要显示今天这顿饭被挑选了多少次,所以我需要时间戳来进行这个查询。

class Meal < ActiveRecord::Base
  def todays_picks
    meal_picks.where(["created_at >= ? AND created_at < ?", Date.today.beginning_of_day, Date.today.end_of_day])
  end
end

在我在 Meal 中只有一个 meal_picked_count 计数器之前,我通过 increment_counter 方法递增。

好的,现在我需要为每个 Canteen 显示拥有最多 MealPicks 的 Meal,我在控制台中玩过并尝试了类似的东西,Canteen.find(1).meals.maximum("meal_picks.count")但这显然不起作用,因为它不是一个列。

有任何想法吗?

4

2 回答 2

6

你可以这样做:

MealPick.joins(:meal => :canteen)
        .where("canteens.id = ?", 1)
        .order("count_all DESC")
        .group(:meal_id)
        .count

这将返回一个这样的有序哈希:

{ 200 => 25 }

200餐点编号在哪里25,计数在哪里。

更新

对于任何感兴趣的人,我开始玩弄这个,看看我是否可以使用 ActiveRecord 的子查询来给我比以前想出的更有意义的信息。这是我所拥有的:

class Meal < ActiveRecord::Base
  belongs_to :canteen
  has_many :meal_picks
  attr_accessible :name, :price
  scope :with_grouped_picks, ->() {
    query = <<-QUERY
      INNER JOIN (#{Arel.sql(MealPick.counted_by_meal.to_sql)}) as top_picks 
      ON meals.id = top_picks.meal_id
    QUERY

    joins(query)
  }

  scope :top_picks, with_grouped_picks.order("top_picks.number_of_picks DESC")
  scope :top_pick, top_picks.limit(1)
end

class MealPick < ActiveRecord::Base
  belongs_to :meal
  attr_accessible :user

  scope :counted_by_meal, group(:meal_id).select("meal_id, count(*) as number_of_picks")
  scope :top_picks, counted_by_meal.order("number_of_picks DESC")
  scope :top_pick, counted_by_meal.order("number_of_picks DESC").limit(1)

end

class Canteen < ActiveRecord::Base
  attr_accessible :name
  has_many :meals
  has_many :meal_picks, through: :meals

  def top_picks
    @top_picks ||= meals.top_picks
  end

  def top_pick
    @top_pick ||= top_picks.first
  end
end

这允许我这样做:

c = Canteen.first
c.top_picks #Returns their meals ordered by the number of picks
c.top_pick  #Returns the one with the top number of picks

假设我想按选择的数量订购所有餐点。我可以这样做:

Meal.includes(:canteen).top_picks #Returns all meals for all canteens ordered by number of picks.
Meal.includes(:canteen).where("canteens.id = ?", some_id).top_picks #Top picks for a particular canteen
Meal.includes(:canteen).where("canteens.location = ?", some_location) #Return top picks for a canteens in a given location

由于我们使用连接、分组和服务器端计数,因此不需要加载整个集合来确定选择计数。这更灵活一点,可能更有效。

于 2012-12-12T21:33:16.427 回答
-1
canteen.meals.max {|m| m.meal_picked_count}
于 2012-12-12T20:56:05.743 回答