class Position < ActiveRecord::Base
belongs_to :product, foreign_key: :symbol
end
class Product < ActiveRecord::Base
has_many :positions, primary_key: :symbol, foreign_key: :symbol
end
When I do
Product.first.positions.first
I am getting a Product back.
But, when I do Position.first.product
I am getting nothing.
When I look at the SQL generated by the query, it is:
SELECT "products.*" FROM "products" WHERE "products.id" = ? LIMIT 1 [["id", 0]]
Why?
The SQL generated is using
products.id
instead ofproducts.symbol
because you didn't tell it that the association should usesymbol
as the primary key instead of the default ofid
. So, in yourPosition
class just addprimary_key: :symbol
to thebelongs_to
and I think that'll do it.