gpt4 book ai didi

ruby-on-rails - Rails has_and_belongs_to_many ActiveRecord::UnknownPrimaryKey

转载 作者:行者123 更新时间:2023-12-04 12:52:01 26 4
gpt4 key购买 nike

我很难建立 has_and_belongs_to 关系。

类别型号:

class Category < ActiveRecord::Base 
has_and_belongs_to_many :products
end

产品型号:
class Product < ActiveRecord::Base
has_many :orders, foreign_key: 'sku', primary_key: 'sku'
has_and_belongs_to_many :categories
end

我正在使用现有数据库,并为所需的所有数据创建模型,将列映射到 Rails 命名约定。

这是 View 的结构:

类别 View :
categories
id
name
category_parent

产品 View :
products
id
sku
price
title

类别产品合并 View :
categories_products
category_id
product_id

这是我在控制台上对此进行的测试,并产生了错误:
2.0.0p247 :017 > Product.first.categories
Product Load (1.0ms) SELECT `products`.* FROM `products` LIMIT 1
ActiveRecord::UnknownPrimaryKey: Unknown primary key for table categories in model Category.

我尝试从产品中删除其他关联,只是为了消除任何冲突的可能性:
has_many :orders, foreign_key: 'sku', primary_key: 'sku' 

但没有它,结果是一样的。

另一个关联工作正常:
Order.first.product
Order Load (2.9ms) SELECT `orders`.* FROM `orders` ORDER BY `orders`.`id` ASC LIMIT 1
Product Load (5.7ms) SELECT `products`.* FROM `products` WHERE `products`.`sku` = '826663144369' LIMIT 1
=> #<Product id: 218464, sku: "1234567890", price: #<BigDecimal:7fabdb577428,'0.2195E2',18(18)>, title: "Blah blah blah">

我使用的是 Ruby 2.0.0p247 和 Rails 4.0.0

最佳答案

我在类别和产品模型中添加了以下内容:

self.primary_key = :id 

我猜测 rails 无法识别用于关联的主键,因为我使用的是 View ,而 View 没有键。

关于ruby-on-rails - Rails has_and_belongs_to_many ActiveRecord::UnknownPrimaryKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com