我有兩個關係(類)集團通過爲SQL count語句多列,在軌環境
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} }
我肯定可以做的又一輪SQL的,一旦我得到的ID或名稱創建一個哈希,但我認爲這不是有效的方法。感謝任何幫助或建議:)
但它似乎很慢。 – 2017-10-30 10:51:22