簡體   English   中英

具有自定義主鍵的Has_many關系不起作用

[英]Has_many relationship with custom primary key not working

我想用Merchant.products調用查詢數據庫。但是我無法使它正常工作。我的主鍵應該是商人表上的商人_標識符,而外鍵是產品表上的外來商人_標識符。 我的架構:

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

然后我的產品表

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM