电商平台物品定制

Items customization in e-commerce platform

我正在 Rails 为餐厅构建一个简单的电子商务平台,以方便在线订购。我想要做的是让 restaurant 独立地自定义它的每个 items。例如,所述餐厅可能希望将 size 添加到一个 item 并针对不同的尺寸增加费用,或者将 flavor 添加到另一个 item,或任何任意属性;此外,不同的项目不一定具有相同的属性。所以基本上,我想让餐厅在创建项目时添加自定义字段。

实现此目标的最佳方法是什么?

谢谢。

试着看看document oriented databases/NOSQL systems, like mongoDB

使用 Postgres 9.2+ 作为数据库后端,您可以轻松实现您的目标。

启用hstore extension(这也可以通过SQL完成)。

class AddExtrasToItems < ActiveRecord::Migration
  def change
    enable_extension "hstore"
    add_column :items, :extras, :hstore
    # I also advice to use gin for indexing 
    # add_index :users, :extras, using: :gin
  end
end

Might be helpful - GIN and GIST

识别这个 属性 (extras) 和 store_accessor (http://api.rubyonrails.org/classes/ActiveRecord/Store.html)

class Item < ActiveRecord::Base
  store_accessor :extras
  ...
end

然后您就可以创建记录,例如

i1 = Item.new
i1.name = 'foo'
i1.type = 'salad'
i1.extras = { size: 'big', vegan: 'yes' }
i1.save

i2 = Item.new
i2.name = 'bar'
i2.type = 'snack'
i2.extras = { flavor: 'mexicana', kosher: 'yes' }
i2.save

正在查询

# Items having flavor
Item.where("extras ? :key", key: "flavor") 

# Items classified as kosher
Item.where("extras @> hstore(:key, :value)",
  key: "kosher", value: "yes"
)

BTW postgres 也有 json 和 jsonb 列类型来存储数据库中的文档。它们也可能有用 - https://www.postgresql.org/docs/9.6/static/datatype-json.html