2012-10-22 24 views
3

我寫了這個數的答覆數量的關聯(至後)計算唯一記錄:如何通過獨特的用戶通過使用Rails的一個範圍3

p = Post.find 1 
r = p.responses.count(:user_id, distinct: true) 

我試圖將其轉換成範圍,但它拋出一個錯誤:undefined method 'default_scoped?' for 30:Fixnum

class Response < ActiveRecord::Base 
    belongs_to :author, class_name: 'User', foreign_key: 'user_id' 
    belongs_to :post 

    scope :by_unique_users, joins(:post).count(:user_id, distinct: true) 
end 

class Post < ActiveRecord::Base 
    belongs_to :user 
    has_many :responses 
end 

class User < ActiveRecord::Base 
    has_many :posts 
    has_many :responses 
end 

回答

1

http://guides.rubyonrails.org/active_record_querying.html#scopes

All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it.

換句話說返回的結果集需要與其他Active Record方法調用進行鏈接;計算不可鏈接,因此你得到的錯誤。隨着中說,如果你絕對要使用範圍,我們需要讓它鏈能夠:

class Response < ActiveRecord::Base 
    scope :unique_responses_for_post, lambda {|post_id| where("post_id = ?", post_id).select(:user_id).uniq } 
end 

您可以根據需要更改名稱,我按照它做什麼它命名。隨着新的範圍定義,你可以這樣做:

p = Post.find 1 
r = Responses.unique_responses_for_post(p.id).count() 

或者

IMO,對於這個問題更好的解決方案是簡單地定義你的Post模型中的實例方法:

def distinct_response_count 
    responses.count(:user_id, :distinct => true) 
end 
+0

有趣的文章,但我認爲陪審團尚未被召喚在這個問題上。範圍仍然非常流行,恕我直言,比方法更好的語法。 – DGM

+0

該文章於2011年4月21日更新,明確指出(a)錯誤是固定的,(b)作者使用範圍簡單的範圍 - 所以這只是大多數用戶的意見。 –

+0

@DaveNewton我提到這個bug已經被修復了,但是感謝評論。我應該在某個時候重新訪問此答案,並可能完全忽略第一部分信息以避免混淆。 – Noz