0
我有Favorite
模型,它允許用戶保存Entries
和Feeds
。過濾相關的多態模型
class User < ActiveRecord::Base
has_many :favorites
has_many :favorite_feeds, :through => :favorites, :source => :favorable, :source_type => "Feed"
has_many :favorite_entries, :through => :favorites, :source => :favorable, :source_type => "Entry"
end
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :favorable, :polymorphic => true
attr_accessible :user, :favorable
end
class Feed < ActiveRecord::Base
has_many :favorites, :as => :favorable
has_many :fans, :through => :favorites, :source => :user
end
class Entry < ActiveRecord::Base
has_many :favorites, :as => :favorable
has_many :fans, :through => :favorites, :source => :user
end
我現在需要顯示網頁上的所有Entries
並註明current_user
是否添加了每個Entry
作爲favourite
。目前呼叫@entry.fans
正在從數據庫中獲取每個User
,這是效率低下的。由於我不需要任何其他記錄,因此我需要一種過濾此調用的方式來僅獲取屬於current_user
的收藏夾。
我可以在我的控制器的內存中執行此操作,但我認爲有一種方法可以簡單地選擇current_user
的收藏夾並使用Active :: Record將其加入Entries
模型。
謝謝。