开发者

Rails - single ID for multiple models

开发者 https://www.devze.com 2023-01-01 12:38 出处:网络
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 associa开发者_Python百科ted items.

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 associa开发者_Python百科ted 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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消