2

我有两个关系(类)

class RecommendedForType < ActiveRecord::Base
   attr_accessible :description, :name
   has_many :recommended_for_type_restaurants
end

class RecommendedForTypeRestaurant < ActiveRecord::Base
   attr_accessible :recommended_for_type_id, :restaurant_id, :user_id
   belongs_to :restaurant
   belongs_to :user
   belongs_to :recommended_for_type

   def self.get_count(rest_id)
     r = RecommendedForTypeRestaurant.where(restaurant_id: rest_id)
     @result =  r.includes(:recommended_for_type)
            .select("recommended_for_type_id, recommended_for_types.name")
            .group ("recommended_tor_type_id, recommended_for_types.name")
            .count
   end

end

如果我打电话

 RecommendedForTypeRestaurant.get_count(1) # get stat of restaurant_id: 1

我明白了

 {"dinner"=>1, "fast food"=>1, "lunch"=>3, "romantic dinner"=>1}

我的目标是 在返回结果中同时获得id和。目前我只能让它返回或者返回。像这样的东西nameRecommendTypeForidname

 {{"id" => 1, "name" => "dinner", "count" => 1}, {"id" =>2, "name" => "lunch", "count" => 3} }

当然,一旦我获得 id 或 name 来创建该哈希,我可以执行另一轮 sql,但我认为这不是有效的方法。感谢任何帮助或建议:)

4

2 回答 2

6

需要单独分组,试试下面的分组。

.group ("recommended_tor_type_id", "recommended_for_types.name").count
于 2015-08-10T16:27:55.587 回答
-1

我相信,如果您.count在最后删除并将其更改select为:

.select("count(*), recommended_for_type_id, recommended_for_types.name")

您将获得一组模型,这些模型将具有您需要的属性和计数。

您应该可以通过执行以下操作在控制台中对其进行测试:

 r = RecommendedForTypeRestaurant.where(restaurant_id: rest_id)
 @result =  r.includes(:recommended_for_type)
        .select("recommended_for_type_id, recommended_for_types.name, count(*)")
        .group ("recommended_tor_type_id, recommended_for_types.name")

 @result.each do |r|
     puts r.recommended_for_type_id
     puts r.name
     puts r.count
 end

希望能帮助到你!

于 2013-04-30T10:25:58.137 回答