0

I need (was ordered) to JOIN two tables by the CODE column (string). But the default (and the proper) way to join tables Product.joins(:skus) is to do so through ID=TABLE_ID What is the best to go about this situation and is there a way to do so without having to write:

Product.joins("INNER JOIN skus ON skus.CODE = products.CODE")

1 Answer 1

3

Based on ActiveRecord's documentation, you can specify the primary_key and foreign_key of a relationship.

product.rb:

class Product < ApplicationRecord
  has_many :skus, foreign_key: :code, primary_key: :code
end

sku.rb:

class Sku < ApplicationRecord
  belongs_to :product, foreign_key: :code, primary_key: :code
end

and now you can simply use Product.joins(:skus) or Product.includes(:skus) or event Product.first.skus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.