Search code examples
ruby-on-railsrubypostgresqlruby-on-rails-4hstore

Dynamic Forms with HStore and rails 4


I was following this railscast, and finished the tutorial. Everything was working fine. Then I decided to use hstore instead of a serialized hash, and after setting up hstore, ran into a error:

PG::Error: ERROR: Syntax error near '!' at position 4 : INSERT INTO "products" ("product_type_id", "created_at", "properties", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"

I googled, and found a similar SO question, but I'm using Rails 4, which supposedly doesn't need to use that gem anymore.

Here's my code:

The relevant portion of my form.html.haml looks like this

= f.fields_for :properties, OpenStruct.new(@product.properties) do |builder|
  - @product.product_type.products.each do |product|
    = render "products/fields/#{product.field_type}", field: field, f: builder

My Product model looks like this:

class Product < ActiveRecord::Base
  belongs_to :product_type
  serialize :properties
end

I can post more code if it will help. Thanks!


Solution

  • The Rails4 PostgreSQL driver for ActiveRecord is supposed to have native support for PostgreSQL's hstore type so you shouldn't need to use serialize at all. Try ditching the serialize.

    BTW, a ! will appear in a YAML string when you attempt to serialize some objects to YAML:

    "--- !ruby/object:SomeClassName ..."
    

    and that ! could cause some problems if PostgreSQL was expecting to see an hstore string.