与自定义主键的Has_many关系不起作用

时间:2015-08-12 12:46:43

标签: mysql ruby-on-rails primary-key has-many

我想使用Merchant.products调用来查询数据库..但是我无法使用它。我的主键应该是商家表上的merchant_identifier,产品表上有外键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

然后是我的产品表

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

1 个答案:

答案 0 :(得分:2)

您还需要指定主键。

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
相关问题