【问题标题】:How to join the parent table when using STI使用 STI 时如何加入父表
【发布时间】:2020-04-28 11:16:24
【问题描述】:

我有这些模型:

class Product < ApplicationRecord
  has_many :units
end

class Unit < Product
  belongs_to :product
end

上面的模型只使用一个表,称为'products'表。

create_table :products do |t|
  t.string  :code
  t.integer :product_id
  t.string  :type
  t.string  :status
  ...
end

我想要的是获取所有units,其中products.status 是active。

我试过Unit.joins(:product).where(products: { status: 'active' }),但没有成功

这是我拥有的当前数据

| id |  type   | product_id | status  |
|----|:-------:|-----------:|---------|
| 1  | Product |       null | deleted |
| 2  | Product |       null | active  |
| 3  |  Unit   |          1 | active  |
| 4  |  Unit   |          1 | active  |
| 5  |  Unit   |          2 | active  |

我只想得到

| id |  type   | product_id | status  |
|----|:-------:|-----------:|---------|
| 5  |  Unit   |          2 | active  |

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-5


    【解决方案1】:

    简答:

    您的用例对使用 STI 没有意义。像这样使用has_many/belongs_to:

    # notice we inherit from ApplicationRecord now instead
    class Unit < ApplicationRecord
      belongs_to :product
    end
    

    然后您可以像这样运行查询:

    Product.joins(:units).where(units: {status: 'active'})
    

    解释:

    在从同一父级继承的两个表之间建立belongs_to -> has_many 关系是没有意义的。带有 STI 的两个表是“这两个模型是更通用模型的特定类型”的另一种说法。

    例如:

    # the parent class your other children classes will inherit from
    class Vehicle < ApplicationRecord
      # and let's say in the database vehicle has a column of:
      # color: :string
    
      def honk
        puts 'beep!'
      end
    end
    
    # Car inherits methods and attributes of Vehicle, and can also define 
    # its own methods particular to cars
    class Car < Vehicle
      def sunroof?
        # logic here
      end
    end
    
    # Motorcycle inherits methods and attributes of Vehicle, and can also define
    # its own methods particular to motorcycles
    class Motorcycle < Vehicle
      def sidecar?
        # logic here
      end
    end
    

    如您所见,STI 的目的是共享常用方法和属性(在上面的示例中,honk 方法和:color 属性),这样您就不会浪费时间并导致潜在的应用程序问题通过定义它们两次。

    相比之下,belongs_to/has_many 关联用于定义两个完全独立但相关的模型之间的关系。例如:

    class Book < ApplicationRecord
      belongs_to :library
    
      ...
    end
    
    class Library < ApplicationRecord
      has_many :books
    
      ...
    end
    

    这将允许我们在应用程序中做一些有用的事情,例如检查给定图书馆可以借出哪些书籍:

    library = Library.first
    library.books
    => # a bunch of book objects returned from the db
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      相关资源
      最近更新 更多