ruby-on-rails - 如何在装饰器中定义关联?
问题描述
我不想用复杂的关联污染我的模型(在 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)
有没有办法创建一个装饰器类,以便可以在其上声明关联(例如预加载关联)?
解决方案
目前还不完全清楚你想要做什么。“声明关联”(装饰器)很可能是一个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
至于“预加载”这个想法,好吧,我不知道该怎么做。
推荐阅读
- bazel - 如果我的 bazel 目标生成未在其输出中指定的文件,我会出错吗?
- laravel-5 - 拉拉维尔 5.6。文件属性不来
- apache-flink - Flink 中的 RocksDBStateBackend 如何将数据溢出到磁盘?
- python - 如何重命名文件以包含文件路径?
- django - 使两个外键在同一模型上唯一
- javascript - moment.js 如何以特定格式打印本周
- android - 创建新项目后activity_main.xml 中的错误
- excel - 将多个值写入一个单元格 - VBA
- python - 字典列表的问题
- python - 在 Python multiprocessing.Process 中,我们是否必须使用 `__name__ == __main__`?