电子商务平台中的项目定制

时间:2017-04-16 22:02:26

标签: ruby-on-rails ruby activerecord e-commerce

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

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

感谢。

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

使用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

使用extrashttp://api.rubyonrails.org/classes/ActiveRecord/Store.html

识别此属性(store_accessor
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