Has_many 与自定义主键的关系无效

Has_many relationship with custom primary key not working

我想通过 Merchant.products 调用查询数据库。但是我无法让它工作。我的主键应该是商家 merchant_identifier table ,在产品 table 上使用外键 merchant_identifier。我的架构:

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

然后是我的产品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"

还有我的模特

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

这是我在尝试获取属于商家的产品时遇到的错误。

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" = ?

您还需要指定主键。

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