如何在 rails 关联中包含来自联接 table 的列?
How can I include a column from a join table in a rails association?
我正在通过连接 table 连接两个模型,以便我可以在关系上设置状态:
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
ProductTest
上有一个 status
列,让我为每个测试将产品从 "active" 切换到 "paused"。
当我使用来自 Test
的 products
关联时,我想在 status
列中合并。我已经在上面一起破解 products_with_status
但想知道是否有更多 "Rails" 方法来做到这一点。
谢谢!
您可以添加新的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
我正在通过连接 table 连接两个模型,以便我可以在关系上设置状态:
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
ProductTest
上有一个 status
列,让我为每个测试将产品从 "active" 切换到 "paused"。
当我使用来自 Test
的 products
关联时,我想在 status
列中合并。我已经在上面一起破解 products_with_status
但想知道是否有更多 "Rails" 方法来做到这一点。
谢谢!
您可以添加新的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