【问题标题】:Filtering associated polymorphic models过滤关联的多态模型
【发布时间】:2013-03-31 18:14:37
【问题描述】:

我有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_users 收藏夹并使用 Active::Record 将其加入 Entries 模型。

谢谢。

【问题讨论】:

    标签: ruby-on-rails-3 activerecord polymorphic-associations


    【解决方案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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 2014-01-26
      • 2011-01-30
      相关资源
      最近更新 更多