加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 22:56:41 所属栏目:百科 来源:网络整理
导读:我有两个型号,产品和产品如下: 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,b
我有两个型号,产品和产品如下:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读