0

사용자가 EntriesFeeds을 저장할 수있는 Favorite 모델이 있습니다.관련된 다형성 모델 필터링

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_userfavouriteEntry를 추가 여부를 나타냅니다. 현재 @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 %>