Rails的4×paper_trail:过滤器版本通过ITEM_ID与嵌套的资源 [英] Rails 4 x paper_trail: filter versions by item_id with nested resources

查看:184
本文介绍了Rails的4×paper_trail:过滤器版本通过ITEM_ID与嵌套的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails应用程序4,我有以下型号:

In my Rails 4 app, I have the following models:

class User < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :calendars, through: :administrations
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Calendar < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :users, through: :administrations
end

class Post < ActiveRecord::Base
    belongs_to :calendar
end

我安装了 paper_trail 宝石来跟踪我的模式的转变中的文档,它就像一个魅力

I installed the paper_trail gem to track changes on my post model as explained in the documentation and it works like a charm.

版本会显示在日历#指数认为,作为一个仪表板的用户

Versions are displayed in the Calendars#Index view, which serves as a dashboard to the user.

下面是我的 CalendarsController 是安装程序:

Here is how my CalendarsController is setup:

def index
  @user = current_user
  @calendars = @user.calendars.all
  @comments = @user.calendar_comments.order("created_at DESC").limit(20)
  @versions = PaperTrail::Version.order('id DESC').limit(10)
end

正如你可以推断从上面的code,问题是,从数据库的所有版本(至少在过去的10个版本)被拉到,无论哪个岗位,他们都涉及到(也是最重要的是,这是否 belong_to A 日历 belong_to CURRENT_USER ,或没有)。

As you may infer from the above code, the problem is that ALL versions (at least the last 10 versions) from the database are pulled, regardless of which post they are related to (and most importantly, whether this post belong_to a calendar that belong_to the current_user, or not).

不过,我们要的是分配给 @versions

However, what we want is to assign to @versions:

  • 所有有关版本
  • 所有的帖子
  • 所有属于日历
  • @user

我想创建取值 ID 的S所有相关后一个数组,并存储成 @posts ,然后存放在 @versions 所有版本其中, ID 包含在 @posts 阵列

I am thinking of creating an array of all the relevant posts ids and store it into @posts and then store in @versions all the versions where the id is included in the @posts array.

但这似乎沉重和处事的方式Rails的不相符。

But this seems heavy and not consistent with the Rails way of doing things.

有关我应该如何进行任何想法?

Any idea about how I should proceed?

推荐答案

您可以使用对象的属性,通过PaperTrail( ITEM_TYPE 提供的ITEM_ID ):

You can make use of object's attributes, provided by PaperTrail (item_type and item_id):

PaperTrail::Version
  .where(item_type: 'Post', item_id: Post.where(calendar_id: @calendars.ids))
  .order('id DESC')
  .limit(10)

这篇关于Rails的4×paper_trail:过滤器版本通过ITEM_ID与嵌套的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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