我有一个包含多个“Feed”的页面。在我的控制器中,我有类似的东西:
def index
@plays = current_user.plays.includes(:game).order("created_at desc")
@wants = current_user.wants.includes(:game).order("created_at desc")
@ratings = current_user.ratings.includes(:game).order("created_at desc")
end
我在视图中使用这样的代码:
<% @plays.each do |play| %>
You played <%= play.game.name %></p>
<% end %>
现在我想在“所有活动”的页面上进行第四次提要,该页面在按创建日期(desc)排序的一个Feed中显示“播放”,“想要”和“评分”。
任何有关最佳方法的帮助都会很棒。
更新:根据每个模型的请求代码,现在简单明了:
class Play < ActiveRecord::Base
attr_accessible :game_id, :user_id, :description
belongs_to :user
belongs_to :game
end
class Rating < ActiveRecord::Base
attr_accessible :game_id, :id, :score, :user_id, :description
belongs_to :user
belongs_to :game
end
class Want < ActiveRecord::Base
attr_accessible :game_id, :user_id, :description
belongs_to :user
belongs_to :game
end
答案 0 :(得分:2)
由于这些来自单独的表,您将无法在数据库查询中对它们进行排序。但由于您已经拥有了每个数组,因此可以使用Ruby进行组合和排序:
@activities = (@plays + @wants + @ratings).sort_by {|a| a.created_at}.reverse
答案 1 :(得分:0)
我可以想到两种方法,快速简便的方式和重构方式。
快速简便的方法是从三者中的每一个构建一个包含所有结果的数组,然后按日期对其进行排序。所以你可以有类似的东西:
@items = [] << @plays << @wants << @ratings
@items.sort_by { |item| item.created_at }
然后你的视图代码可以询问每个项目它的类是什么来确定要使用的文本。
重构的方式是注意到你的3个类几乎完全相同 - 事实上,除了名称之外,Play和Want是相同的,而Rating只添加一个列。因此,为所有3添加超类。您可能需要进行巧妙的迁移,以使用STI将数据库表合并到单个表中,但它可能是更好的长期解决方案。