Rails:belongs_to 和 has_many 使用非标准 ID [英] Rails : belongs_to and has_many using non-standard ids

查看:32
本文介绍了Rails:belongs_to 和 has_many 使用非标准 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,Item 和 Product,如下所示:

I've got two models, Item and Product as follows:

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, 
           created_at: datetime, updated_at: datetime)

将此视为属于特定产品的项目.

Think of this as an item is of a particular product.

我设法通过

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

但我似乎无法引用特定项目的产品.这就是我现在所拥有的:

but I can't seem to refer the Product of a particular item. This is what I've got now:

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

就我的理解而言:就数据库而言,这应该可行.除了它没有.也许我在这里错过了什么?我对 Rails 相当陌生(大约一个月或更短时间.)

And as far as my understanding re: databases are concerned, that should work. Except that it doesn't. Maybe I'm missing out on something here? I'm fairly new to rails (around a month or less.)

推荐答案

它必须是 belongs_to 吗?既然你指定了主键和外键,为什么不

Does it have to be a belongs_to? Since you're specifying both primary and foreign key, why not

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

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

这篇关于Rails:belongs_to 和 has_many 使用非标准 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆