2013-09-30 32 views
1

我有一個User模型,其中用戶可以「彼此最喜歡」。我通過Favoriting模型作爲has_many through關係實現這一參考User本身:方法通過關係給has_many的最愛數量

class User < ActiveRecord::Base 
    has_many :favoriting 
    has_many :favorites, through: :favoritings, source: :favorited 
    has_many :favoriteds, class_name: "Favoriting", foreign_key: "favorited_id" 
    has_many :favoriters, through: :favoriteds, source: :user 
    ... 
end 

class Favoriting < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :favorited, :class_name => 'User' 
    ... 
end 

這一切的偉大工程。我可以做u.favorites並獲得用戶的收藏夾,並且我可以通過u.favoriters獲得已收藏的用戶u。我也可以做u.favorites_count以獲得最愛的數量。

但是,我不能這樣做u.favoriters_count以獲得已收藏的用戶數u

任何想法是否有權訪問內置方法favoriters_count甚至favoriteds_count與這種類型的DB關係?我可以編寫自己的代碼,但寧願將代碼基本保持爲簡單,並儘量使用「Rails-y」。

回答

3

您是否考慮過在favoritings_count列中添加counter_cache

+0

我正在尋找一個沒有附加數據庫操作的解決方案,我已經加載了'User'模型,所以我需要從'User'模型的計數器列中讀取。 – tyler

+0

你有沒有考慮添加'counter_cache '' –

+0

我已經嘗試過兩個'belongs_to'調用,分別和一起。它只是拋出錯誤,缺乏'favoritings_count'列。 ather不會重命名跟蹤列,但我可能會盡快嘗試。 – tyler

0

不,has_many添加的方法在http://guides.rubyonrails.org/association_basics.html的4.3.1中列出,並且不包含通過該名稱的方法。

+0

這聽起來是對的,但它也沒有在文檔中列出'favorites_count',並且即使在'Favoriting'模型中沒有定義'counter_cache:true',我也可以訪問該方法... – tyler

+0

我知道你想出了一個'favoritings_count'列和使用'counter_cache',但你會介意檢查'favorites_count'的定義(例如'user.method(:favorites_count)'和'user.method(:favorites_count).source_location' ? –