我想選擇大多數用戶使用的資源。如何創建範圍以選擇大多數用戶使用的記錄
型號:
class Resource < ActiveRecord::Base
has_many :users, :through => :kits
has_many :kits
class User < ActiveRecord::Base
has_many :resources, :through => :kits
has_many :kits, :dependent => :destroy
class Kit < ActiveRecord::Base
belongs_to :resource
belongs_to :user
我希望創建一個選擇其resource.users.count這些資源範圍> 3
我怎樣才能在Rails的做到這一點?
感謝
我越來越接近,但仍然有一些問題:
scope :most, group('resources.id, resources.title, resources.url, resources.description, resources.author, resources.price, resources.created_at, resources.updated_at').joins(:users).having("count(user_id) > ?",5)
我不得不包括對資源的所有字段,因爲PostgreSQL是給了一個錯誤如下:
ActiveRecord::StatementInvalid: PG::Error: ERROR: column "resources.category_id" must appear in the GROUP BY clause or be used in an aggregate function
必須有一種方法來包含所有的字段,而不必輸入每個字段
您好感謝西奧,有沒有辦法在一個範圍內做到這一點? – chell
@chell在上面的答案中查看我的編輯。如果你仍然需要幫助,請粘貼你的SQL,我會爲你轉換它。 –
嗨西奧我會給它一個鏡頭,並得到回覆,謝謝你百萬 – chell