Rails - 多个模型的单一 ID

发布于 2024-09-03 09:47:24 字数 277 浏览 2 评论 0原文

我正在构建一个应用程序,允许用户扫描“货架”、“盒子”或“产品”上的条形码,然后显示该特定项目或所有相关项目。

由于这些都是具有自己 ID 的独立模型,因此我需要一个全局 ID 表。

我正在考虑一个名为“条形码”的多态表

barcodes

  • id
  • Barcode_number
  • barcodable

有没有一种简单的方法可以做到这一点?或者说多态是最好的方法?

I'm building an app which will allow a user to scan the barcode on a 'shelf', 'box' or 'product' which will then bring up that particular item or all the associated items.

As these are all separate models with their own ID's, I need a global ID table.

I was thinking of a polymorphic table called 'barcodes'

barcodes

  • id
  • barcode_number
  • barcodable

Is there an easy way to do this? Or is polymorphic the best way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌酱 2024-09-10 09:47:24

创建一个模型 Barcode (最终将有一个字段 numbercode):

class Barcode < ActiveRecord::Base
end

然后,每个具有条形码的模型都会有一个字段名为 barcode_id 的表:

class Shelf < ActiveRecord::Base
  belongs_to :barcode
end

class Box < ActiveRecord::Base
  belongs_to :barcode
end

class Product < ActiveRecord::Base
  belongs_to :barcode
end

您将可以像这样访问该条形码:

@shelf.barcode

Create a model Barcode (which will eventually have a field number or code):

class Barcode < ActiveRecord::Base
end

Then, every model that has a barcode will have a field in the table named barcode_id:

class Shelf < ActiveRecord::Base
  belongs_to :barcode
end

class Box < ActiveRecord::Base
  belongs_to :barcode
end

class Product < ActiveRecord::Base
  belongs_to :barcode
end

And you will have access to that barcode like this:

@shelf.barcode
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文