我有两个关系(类)
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
和。目前我只能让它返回或者返回。像这样的东西name
RecommendTypeFor
id
name
{{"id" => 1, "name" => "dinner", "count" => 1}, {"id" =>2, "name" => "lunch", "count" => 3} }
当然,一旦我获得 id 或 name 来创建该哈希,我可以执行另一轮 sql,但我认为这不是有效的方法。感谢任何帮助或建议:)