【发布时间】:2018-08-22 16:57:22
【问题描述】:
我不想用复杂的关联来污染我的模型(在 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)
有没有办法创建一个装饰器类,以便可以在其上声明关联(例如预加载关联)?
【问题讨论】:
-
有什么办法可以做什么,究竟是什么?
-
@jvillian 添加装饰器,因此可以在其中定义关联
-
我能想到的唯一方法是让你的装饰器成为
ActiveRecord::Base的子类——关联是在 AR 中为每个类定义的。我会说这是对设计模式的过度应用。
标签: ruby-on-rails associations decorator