2013-03-31 113 views
0

我有Favorite模型,它允許用戶保存EntriesFeeds過濾相關的多態模型

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模型。

謝謝。

回答

1

控制器:

@entries = Entry.all 
@user_favorite_entry_ids = current_user.favorite_entries.pluck(:id) 

查看:

<% @entries.each do |entry| %> 
<%= @entry.id %>: <%= @entry.id.in?(@user_favorite_entry_ids) ? 'favorite of current user' : 'not' %> 
<% end %> 

或者,如果你真的很喜歡在數據庫中做的事情:

@entries = Entry.select('entries.*, count(favorites.id) as current_user_favorite').joins("left join favorites on favorites.favorable_id = entries.id and favorites.favorable_type = 'Entry' and favorites.user_id = #{current_user.id}") 

然後:

<% @entries.each do |entry| %> 
    <%= @entry.id %>: <%= (@entry.current_user_favorite.to_i > 0) ? 'favorite of current user' : 'not' %> 
<% end %> 
相關問題