Rails 4 x paper_trail:使用嵌套资源按 item_id 过滤版本

Rails 4 x paper_trail: filter versions by item_id with nested resources

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

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 gem 来跟踪我的 post 模型的变化,如 the documentation 中所述,它非常有效。

版本显示在 Calendars#Index 视图中,该视图用作 user 的仪表板。

这是我的 CalendarsController 的设置方式:

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

正如您可能从上面的代码中推断的那样,问题是从数据库中提取了所有版本(至少最近 10 个版本),无论它们与哪个 post 相关(最重要的是, 是否这个 post belong_to 一个 calendarbelong_to current_user, 或者不是).

然而,我们想要的是赋值给@versions:

我正在考虑创建一个包含所有相关 post id 的数组并将其存储到 @posts 中,然后将所有版本存储在 @versionswhere id 包含在 @posts 数组中。

但这看起来很沉重,并且不符合 Rails 做事方式。

知道我应该如何进行吗?

您可以使用 PaperTrail(item_typeitem_id)提供的对象属性:

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