使用外引号保存Rails数组

时间:2015-09-30 00:51:37

标签: ruby-on-rails ruby

是否可以在没有外引号的情况下保存以下数组?或者是否可以在没有外引号的情况下访问数组?

e.hours = "5:30AM", "6:00AM", "6:30AM"
# => ["5:30AM", "6:00AM", "6:30AM"] 
e.save
   (0.2ms)  begin transaction
  SQL (1.6ms)  UPDATE "brands" SET "hours" = ?, "updated_at" = ? WHERE "brands"."id" = ?  [["hours", "[\"5:30AM\", \"6:00AM\", \"6:30AM\"]"], ["updated_at", "2015-09-30 00:35:25.117927"], ["id", 1]]
   (6.8ms)  commit transaction
# => true 
e
# => #<Brand id: 1, name: "Starbucks", created_at: "2015-09-23 22:59:08", updated_at: "2015-09-30 00:35:25", hours: "[\"5:30AM\", \"6:00AM\", \"6:30AM\"> 

这就是迁移的样子:

add_column :brands, :hours, :string, array: true, default: []

当我尝试访问控制器中的数组时,它返回带有外引号的数组:

[1] pry(#<OrdersController>)> @delivery_hours
# => "[\"5:30AM\", \"6:00AM\", \"6:30AM\"]"

2 个答案:

答案 0 :(得分:2)

在order.rb文件中,添加以下内容:

serialize :hours, Array

答案 1 :(得分:2)

Rails以JSON格式存储数组记录,因此您只需将JSON更改为数组。

JSON.parse("[\"5:30AM\", \"6:00AM\", \"6:30AM\"]")
# => ["5:30AM", "6:00AM", "6:30AM"]