2012-06-13 22 views
0

我想選擇大多數用戶使用的資源。如何創建範圍以選擇大多數用戶使用的記錄

型號:

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 

必須有一種方法來包含所有的字段,而不必輸入每個字段

回答

0

這應該工作:

class Resource < ActiveRecord::Base 
    def popular_resources 
    joins(:users).where("users.count > '3'") 
    end 
0

雖然效率有點低,但仍然有效:

在類Resource中,創建一個迭代遍歷每個資源的類方法,並將具有超過「num」個用戶數量的每個資源追加到數組中。

def self.more_than_x_users(num) 
    resource_list = [] 
    Resource.all.each |res| 
    if res.users.count > num 
     resource_list << res 
    end 
    end 
    return resource_list 
end 

另一種方法是使用find方法有:選擇和:在this post建議組但你仍然需要返回的外鍵轉換爲對象。我會保持簡單,並採取上述解決方案。

編輯
嘗試一些東西出來之後,我覺得這可能會幫助您:
在你Kit類添加一個範圍如下:

scope :most_used, group(:resource_id).having("count(user_id) > 3") 

如果這行不通因爲我的領域是錯誤的,想想你將如何在SQL語句中做到這一點,並嘗試複製我給你的東西,通過鏈接類似於我的命令。如果您仍然陷入困境,請粘貼您的SQL語句,然後將其轉換爲適合您的範圍。

希望這有助於

+0

您好感謝西奧,有沒有辦法在一個範圍內做到這一點? – chell

+0

@chell在上面的答案中查看我的編輯。如果你仍然需要幫助,請粘貼你的SQL,我會爲你轉換它。 –

+0

嗨西奧我會給它​​一個鏡頭,並得到回覆,謝謝你百萬 – chell