group_by使用其他模型的值

时间:2011-04-09 07:24:57

标签: ruby-on-rails

使用ROR 2.3.8

我在cities_controller.rb

中有这个
@shops = Shop.published.search params[:keyword], {
      :conditions     => conditions,
      :star           => true,
      :group_by       => 'city_id',
      :group_function => :attr,
      :page           => params[:page]
    }.merge(:order => 'rating_average DESC')
@cities = @shops.collect { |shop| shopy.city }

如何告诉Rails从City模型而不是Shop模型获取rating_average?因为Shop模型没有rating_average。它实际上是City模型被评级。

谢谢。

更新

published

中的

Shop.rb名称范围

 sphinx_scope(:published) { 
  {:conditions => {:status => 'published'}}
}

Shop.rb

中的索引
  define_index do
    indexes city.name, :as => :name, :sortable => true
    indexes city.duration, :as => :duration
    indexes city.status, :as => :status
    #has city.budget, :as => :budget
    #has city(:created_at), :as => :created_at
    has city(:rating_average), :as => :rating_average
    has city_id
  end

更新2

class City < ActiveRecord::Base
  has_many :shops, :dependent => :destroy    
  ...
end

1 个答案:

答案 0 :(得分:0)

您应该使用联接来实现此目的:

@shops = Shop.published.search params[:keyword], {
      :conditions     => conditions,
      :star           => true,
      :group_by       => :city_id,
      :group_function => :attr,
      :page           => params[:page]
    }.merge(:order => :rating_average,
            :sort_mode => :desc)

您还应在列之前添加cities.shops.以指定哪个表的列。