首页 > 解决方案 > 如何在装饰器中定义关联?

问题描述

我不想用复杂的关联污染我的模型(在 AR 模型中只有必要的验证和简单的关联)

class Post < ActiveRecord::Base
  has_many :visible_comments,
    -> {
      where(deleted_at: nil).joins(:user).where(users: { active: true }) 
    }, class_name: 'Comment'
end

我想将此关联移动到帖子的装饰器类中

PostsDecorator.new(posts).preload(:visible_comments)

有没有办法创建一个装饰器类,以便可以在其上声明关联(例如预加载关联)?

标签: ruby-on-railsassociationsdecorator

解决方案


目前还不完全清楚你想要做什么。“声明关联”(装饰器)很可能是一个XY Problem

为什么不做类似的事情:

class PostsDecorator < SimpleDelegator

  def visible_comments
    Comment.where(post: component, deleted_at: nil)
  end

private

  def component
    @component ||= self.__getobj__
  end

end

(或类似的规定。)

然后你就可以做到:

PostsDecorator.new(posts).visible_comments

至于“预加载”这个想法,好吧,我不知道该怎么做。


推荐阅读