ruby-on-rails – Rails:belongs_to和has_many使用非标准ids

我有两个型号,产品和产品如下:
irb(main):007:0> Item
=> Item(id: integer,identification_number: string,production_date: date,created_at: datetime,updated_at: datetime,going_in: boolean)
irb(main):008:0> Product
=> Product(id: integer,sku: string,barcode_identification: string,updated_at: datetime)

想想这是一个特定产品的项目.

我已经设法引用了特定产品的所有项目(Product.find(1).items)

class Product < ActiveRecord::Base
  has_many :items,:foreign_key => "identification_number",:primary_key => "barcode_identification"
end

但我似乎无法提及特定项目的产品.
这就是我现在所做的:

class Item < ActiveRecord::Base
  set_primary_key :identification_number
  belongs_to :product,:foreign_key => "barcode_identification"
end

就我的理解而言,数据库是关键的,那应该是有效的.除了它没有.也许我错过了这里的东西?我相当新的轨道(约一个月或更少).

解决方法

它必须是belongs_to吗?既然你指定了主键和外键,为什么不这样做
class Product < ActiveRecord::Base
  has_many :items,:primary_key => "barcode_identification"
end

class Item < ActiveRecord::Base
  has_one :product,:foreign_key => "barcode_identification",:primary_key => "identification_number"
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...