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ページにALL を表示し、 がそれぞれを としてcurrent_user追加したかどうかを示す必要があります。現時点では、呼び出しはデータベースからすべてを取得していますが、これは非効率的です。他のレコードは必要ないため、この呼び出しをフィルタリングして、に属するお気に入りのみをフェッチする方法が必要です。Entryfavourite@entry.fansUsercurrent_user

コントローラーのメモリ内でこれを行うことができますが、current_userお気に入りを選択して、 EntriesActive::Record を使用してモデルに結合する方法があると考えています。

ありがとう。

4

1 に答える 1

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 %>
于 2013-04-01T01:29:16.940 に答える