belongs_to with foreign_key not working in one direction

1k views Asked by At
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?

3

There are 3 answers

1
neuronaut On BEST ANSWER

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.

0
Arslan Ali On

First of all, you need to revise the creation of your model Product.

You need to create it the following way:

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products, id: false do |t|
      t.string :symbol, null: false

      t.timestamps
    end

    add_index :products, :symbol, unique: true
  end
end

And then let your model know about the primary_key, that is not id:

class Product < ActiveRecord::Base
  self.primary_key = "symbol"
end

And after that, when you do Product.last, it will generate the following query:

Product.last
# Product Load (0.3ms)  SELECT  "products".* FROM "products"  ORDER BY "products"."symbol" DESC LIMIT 1
0
Mark Swardstrom On

Try this:

class Product < ActiveRecord::Base
  self.primary_key = "symbol"
end