2017-04-16 32 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

相關問題