Rails:belongs_to 和 has_many 使用非标准 ID
我有两个模型,项目和产品,如下所示:
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)
将其视为特定产品的项目。
我已设法通过引用特定产品 (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
就我对数据库的理解而言,这应该可行。但事实并非如此。也许我在这里错过了一些东西?我对 Rails 相当陌生(大约一个月或更短时间。)
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.
I've managed to refer all the items of a particular product (Product.find(1).items) via
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
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它必须是
belongs_to
吗?既然您指定了主键和外键,为什么不呢Does it have to be a
belongs_to
? Since you're specifying both primary and foreign key, why not您的 items 表中必须有一个外键。
我假设条形码_识别_id 是项目表中的一列(外键)。
如果您有其他列,则只需将其替换为该列即可。
尝试这样:
You must have a foreign key in your items table.
I'm assuming barcode_identification_id is a column (foreign key) in items table.
If you have some other column then just replace it with that.
Try like this: