Search code examples
mysqlruby-on-railsprimary-keyhas-many

Has_many relationship with custom primary key not working


I want to query the db with a Merchant.products call.. But I can't get this to work.. My primary key should be merchant_identifier on the merchants table, with the foreign key merchant_identifier on the products table. My schema:

create_table "merchants", id: false, force: :cascade do |t|
  t.string "merchant_identifier", null: false
  t.string "name"
  t.string "token"
  t.datetime "created_at",          null: false
  t.datetime "updated_at",          null: false
end

 add_index "merchants", ["merchant_identifier"], name: 
 "index_merchants_on_merchant_identifier", unique: true

And then my products table

create_table "products", force: :cascade do |t|
  t.text     "title"
  t.text     "sellersku"
  t.string   "merchant_identifier"
  t.datetime "created_at",          null: false
  t.datetime "updated_at",          null: false
end

add_index "products", ["merchant_identifier"], name: 
"index_products_on_merchant_identifier"

And my models

class Product < ActiveRecord::Base
  belongs_to :merchant, foreign_key: "merchant_identifier"
end

class Merchant < ActiveRecord::Base
  self.primary_key = 'merchant_identifier'
  has_many :products
end

This is the error I get when I try to get products that belong to a merchant..

SELECT "products".* FROM "products" WHERE "products"."merchant_id" = ?  
[[nil, "A340I3BHJ03NV9"]]SQLite3::SQLException: no such column: 
products.merchant_id: SELECT "products".* FROM "products" WHERE 
"products"."merchant_id" = ?
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: 
products.merchant_id: SELECT "products".* FROM "products" WHERE 
"products"."merchant_id" = ?

Solution

  • You need to specifiy the primary key as well.

    class Product < ActiveRecord::Base
      belongs_to :merchant, :foreign_key => 'merchant_identifier', :primary_key => 'merchant_identifier'
    end
    
    class Merchant < ActiveRecord::Base
      has_many :products, :foreign_key => 'merchant_identifier', :primary_key => 'merchant_identifier'
    end