从一个模型类引用几个模型 - 糟糕的做法?

时间:2016-05-27 09:19:11

标签: ruby-on-rails ruby design-patterns model refactoring

我想使用以下代码获取当前用户的所有通知:

current_user.follows.each do |follow|
    follow.followable.open_notifications.each do |notification|
        if !notification.reads.include?(current_user)
            @open_notifications += notification 
        end
    end
end

到目前为止,我在控制器中有这个代码但是我知道这种逻辑应该放在模型类中。 移动代码后:

OpenNotification控制器:

OpenNotification.fetch_unread(current_user) 

OpenNotification模型:

def self.fetch_unread(user)
    @open_notifications = []
    user.follows.each do |follow|
        follow.followable.open_notifications.each do |notification|
            if !notification.reads.include?(user)
                @open_notifications += notification 
            end
        end
    end
    @open_notifications
end

修改

涉及的课程:

  • 用户
  • 关注 - 谁(用户)遵循(跟随)
  • 可跟随(多态 - 可能是用户,事件或地点)
  • OpenNotification - 存储有关可跟随对象更改的信息
  • 读取 - 谁读取了哪个通知(user_id和open_notification_id)

用户:

has_many :follows, class_name: 'Follow',
                 source: :user

has_many :follows_as_fallowable, 
                class_name: 'Follow',
                as: :followable

has_many :followers, through: :follows_as_fallowable,
                   source: :user

事件:

has_many :follows, as: :followable
has_many :followers, through: :follows,
                         source: :user

has_many :open_notifications, as: :followable  

OpenNotification:

belongs_to :followable, polymorphic: true
has_many :reads

读取:

belongs_to :user
belongs_to :open_notification

我的问题是,从负责某个特定资源的类中引用多个类是否是一个好习惯? 如果这不是一个好的做法,那么代码应该如何重构?

1 个答案:

答案 0 :(得分:0)

只要您可以合理地说您的通知模型应该知道用户模型(基本上大多数通知交互也与用户交易?),从一个模型中引用几个模型就完全没问题了。在你在这里展示的一点点,我会说它确实如此,你将不得不考虑这个问题的应用范围,并重新评估它。如果你认为这可能有点延伸,我建议将这个逻辑封装到一个单独的类中,以保证代码更易于维护和可预测,如果有人要与你合作(想想服务对象)。此外,在您向@open_notifications附加通知的地方,您应该考虑使用<<,因为每次都不会重建@open_notifications对象,而+=会一遍又一遍地实例化,为此留下更多的工作垃圾收集器。在大型操作中,您将看到速度大幅增加。

相关问题