user341493
user341493

Reputation: 414

How can I include a column from a join table in a rails association?

I am joining two Models with a join table so that I can put a status on the relation:

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

There is a status column on ProductTest that let's me toggle a a product from "active" to "paused" for each test.

I'd like to merge in the status column when I use the products association from Test. I've hacked together products_with_status above but was wondering if there is a more "Rails" way to do this.

Thanks!

Upvotes: 1

Views: 844

Answers (1)

PGill
PGill

Reputation: 3521

You can add a new has_many association

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

Then you can do

Test.find(1).products_with_status.first.status

Upvotes: 1

Related Questions