Rails:创建“所有活动供稿”来自多个模型 [英] Rails: Creating an "All activity feed" from multiple models

查看:77
本文介绍了Rails:创建“所有活动供稿”来自多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中包含多个 Feed。在我的控制器中,我有这样的东西:

I have a page that has several "Feeds". In my controller I have something like this:

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

,并且我在视图中使用如下代码:

and I use code like this in the view:

   <% @plays.each do |play| %>
          You played <%= play.game.name %></p>
   <% end %>

现在,我想在显示播放的所有活动页面上进行第四次提要,

Now I want to make a forth feed on the page that is "all activity" which displays Plays, Wants and Ratings in one feed sorted by created date (desc).

在一个供稿中按创建日期(desc)排序的需求和评分。

Any help on the best way to do this would be great.

更新:根据每个模型的请求代码,现在很简单:

UPDATE: As requested code from each model, nice and simple right now:

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


推荐答案

由于这些来自单独的表,因此您将无法在数据库查询中对它们进行排序。但由于您已经拥有每个数组,因此可以使用Ruby进行组合和排序:

Since these come from separate tables, you won't be able to sort them in the database query. But since you already have each of the arrays, you can use Ruby to combine and sort:

@activities = (@plays + @wants + @ratings).sort_by {|a| a.created_at}.reverse

这篇关于Rails:创建“所有活动供稿”来自多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆