【问题标题】:Rails 5, Concerns - can they reference a database table?Rails 5,关注点 - 他们可以引用数据库表吗?
【发布时间】:2023-03-22 03:44:02
【问题描述】:

我正在努力了解疑虑。

我可以找到的大多数博客文章和示例都在将模型中定义的类方法移动到公共存储库的上下文中讨论它们。我明白那部分。

我不明白是否可以使用关注点来减少关联模型的设置。例如,我有一个用户模型和一个组织模型。每个用户和组织都有一个地址。

如果address是一个模型,它将是多态的,属于可寻址的。然后用户和组织将各有一个地址。

我正在尝试了解是否可以解决问题,然后将其包含在我的用户和组织模型中。如果是这样,我还能在数据库中有一个名为地址的表吗?如果我没有名为 address 的模型(如果我使用模型文件夹中的关注子文件夹来定义地址,则不需要它),我不清楚我是否可以拥有 db 表。

【问题讨论】:

  • 如果您需要访问数据库表而不是担心它,您可能应该创建模型。担心的是减少班级不应该承担的额外责任。例如,假设您有一个模型类:Product,现在您需要为 db 中的所有产品创建 CSV 导出功能。一种方法是在产品类中扩展此功能,或者创建一个单独的关注类来处理它。 Concern 在 SOLID 中是“S”,这意味着您的班级应该只处理一项职责。如果以后需要导出 xls/json 怎么办?
  • 好的,谢谢。

标签: ruby-on-rails ruby separation-of-concerns activesupport-concern


【解决方案1】:

是的,您当然可以这样做,这很常见。您仍然需要数据库中的Address 模型和addresses 表。

看起来像这样:

# your user model (backed by users table)
class User < ApplicationRecord
   include Addressable
end

# your organisation model (backed by organisations table)
class Organisation < ApplicationRecord
  include Addressable
end

# your address model (backed by addresses table)
class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true, touch: true
end

# the concern to DRY up shared relation that both user adn organisation have
module Addressable
  extend ActiveSupport::Concern

  included do
    has_one :address, as: :addressable, dependent: :destroy
  end
end

【讨论】:

    猜你喜欢
    • 2016-10-08
    • 2014-01-30
    • 2019-12-04
    • 1970-01-01
    • 2011-10-09
    • 2019-11-04
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多