Search code examples
ruby-on-railsrubypostgresqlhstore

Stop rails from escaping hstore array in views


I'm trying to use a postgreSQL column of type hstore array and everything seems to work just fine. However, my views escapes the array and turns it to bad formatted string. My code looks like that:

Migration:

class AddVariantsToItem < ActiveRecord::Migration
  def change
    execute 'CREATE EXTENSION hstore'
    add_column :items, :variants, :hstore, array: true, default: []
  end
end

And now, if i will, for instance, use Item.last.variants in rails console, it gives me a proper array

> Item.last.variants
#=> [{"name"=>"Small", "price"=>"12.00"}, {"name"=>"Medium", "price"=>"20.00"}]

However, using the exact same code in slim views gives me a escaped string:

div
  = debug Item.last.variants

  / Gives me: 
  / '{"\"name\"=>\"Small\", \"price\"=>\"12.00\"","\"name\"=>\"Medium\", \"price\"=>\"20.00\""}'

Using raw, == or .html_save does not changes anything. Can anyone tell me if i can do anything about it?


Solution

  • Item.last.variants is an Array. When putting something into view, its being stringified (I'm not sure, but I think its to_s method or inspect).

    My advice is that you shouldn't put whole objects. In this particular example, I think you should iterate over it and show data manually.