Search code examples
ruby-on-railsforeign-keysbelongs-to

belongs_to with foreign_key not working in one direction


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?


Solution

  • The SQL generated is using products.id instead of products.symbol because you didn't tell it that the association should use symbol as the primary key instead of the default of id. So, in your Position class just add primary_key: :symbol to the belongs_to and I think that'll do it.