2014-02-17 51 views
2

有沒有辦法限制可以保存hstore列?我已經得到了如下代碼:如何更新Rails 4中的hstore列

store_accessor :widget_locations, :left_area1, :mid_area1, :left_area2, :mid_area2, :right_area2 

但這似乎仍然允許其他鍵名保存即, middle_area123

我怎麼能夠更新hstoreupdate_attributesupdate

回答

4

我可能是錯的,但我的猜測是,你是在widget_locations撥打電話一樣

item.widget_locations[:left_area1] = thing 

如果是這樣,你應該改變,要

item.left_area1 = thing 

,因爲你告訴store_accessor創建屬性:left_area1, :mid_area1, :left_area2, :mid_area2, :right_area2將被序列化到數據庫列:widget_locations。現在,這些屬性會像正常屬性,所以你可以把驗證他們等

這也可以讓你更新項目和往常一樣:

item.update(name: 'Test', left_area: 'garden', mid_area: 'livingroom') 

hstore美中不足的是,訪問序列化列允許您添加新的未知屬性,因此最好直接訪問您明確指定的屬性。