【发布时间】:2013-03-31 18:14:37
【问题描述】:
我有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_users 收藏夹并使用 Active::Record 将其加入 Entries 模型。
谢谢。
【问题讨论】:
标签: ruby-on-rails-3 activerecord polymorphic-associations