2017-04-16 61 views
0

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

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

感谢。

回答

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

的识别这个属性(extras)与store_accessorhttp://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" 
) 

顺便说一句,postgres也有json和jsonb列类型来存储文件在你的数据库。他们也可能是有用的 - https://www.postgresql.org/docs/9.6/static/datatype-json.html

+0

非常感谢! – amrrbakry