我有一個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」。
我正在尋找一個沒有附加數據庫操作的解決方案,我已經加載了'User'模型,所以我需要從'User'模型的計數器列中讀取。 – tyler
你有沒有考慮添加'counter_cache '' –
我已經嘗試過兩個'belongs_to'調用,分別和一起。它只是拋出錯誤,缺乏'favoritings_count'列。 ather不會重命名跟蹤列,但我可能會盡快嘗試。 – tyler