如何在Rails关联中包含联接表中的列?

问题描述 投票:1回答:1

我正在使用联接表联接两个模型,以便可以在关系上放置状态:

class Test < ApplicationRecord
  has_many :products_tests
  has_many :products, through: :products_tests

  def products_with_status
    products_tests = ProductsTest.includes(:product).where(test_id: id)
    products_tests.map do |products_test|
      products_test.product.as_json.merge(status: products_test.status)
    end
  end

end

class Products < Application Record
  has_many :products_tests
  has_many :tests, through: :products_tests
end

class ProductsTest < ApplicationRecord
  belongs_to :product
  belongs_to :test
end

status上有一个ProductTest列,让我为每个测试将产品从“有效”切换为“已暂停”。

当我使用status中的products关联时,我想在Test列中合并。我在products_with_status上面一起砍过,但想知道是否还有其他“ Rails”方法可以做到这一点。

谢谢!

ruby-on-rails associations jointable
1个回答
1
投票

您可以添加新的has_many关联

has_many :products_with_status, -> { joins(:products_tests).select("DISTINCT products.*, products_tests.status") }, through: :products_tests, class_name: "Product", source: :product

那么你可以做

Test.find(1).products_with_status.first.status
© www.soinside.com 2019 - 2024. All rights reserved.