Question

I am trying to make hstore work with sinatra 1.4.4 and sinatra-activerecord (1.5.0) in a Postgre database

I work with ruby-1.9.3-p392 with the gems

gem 'sinatra'
gem 'thin'
gem 'sinatra-formhelpers'
gem 'pg'
gem 'activerecord'
gem "sinatra-activerecord"
gem 'rake'
gem 'activerecord-postgres-hstore'
gem 'activesupport'
group :development, :test do
  gem 'rspec'
  gem 'capybara'
  gem 'pry'
end

These are my migrations:


class AddHstore < ActiveRecord::Migration
  def up
    execute 'CREATE EXTENSION hstore'
  end

  def down
    execute 'DROP EXTENSION hstore'
  end
end

class CreateEngineParameters < ActiveRecord::Migration

  def self.up
    create_table :engine_parameters do |t|
      t.hstore :kind
      t.timestamps
    end
  end

  def self.down
    drop_table :engine_parameters
  end
end

With these lines in the model engine_parameter.rb:

require 'active_record'
require 'activerecord-postgres-hstore'

class EngineParameter < ActiveRecord::Base
  serialize :kind, ActiveRecord::Coders::Hstore
end

Then when in console I want to create an object with hstore:

a = EngineParameter.new
=> #<EngineParameter id: nil, kind: {}, created_at: nil, updated_at: nil>
a.kind['test'] = "test"
=> "test"
a
=> #<EngineParameter id: nil, kind: {"test"=>"test"}, created_at: nil, updated_at: nil>
a.save
NoMethodError: undefined method `scan' for {"test"=>"test"}:Hash
from /Users/mycomputername/.rvm/gems/ruby-1.9.3-p392@myproject/gems/pg-hstore-1.2.0/lib/pg_hstore.rb:24:in `load'

Then I tried again :

a.save
NoMethodError: undefined method `map' for "\"test\"=>\"test\"":String
from /Users/mycomputername/.rvm/gems/ruby-1.9.3-p392@myproject/gems/pg-hstore-1.2.0/lib/pg_hstore.rb:49:in `dump'

I didn't found the answer to my question. The closest was here : https://gist.github.com/bru/3258069, but wasn't enough.

There is something I do wrong, but can't find what.

Was it helpful?

Solution

Ok, I found the answer shortly after I asked the question.

With the new activerecord, even on sinatra, you just have to put this

require 'active_record'
require 'activerecord-postgres-hstore'

class EngineParameter < ActiveRecord::Base

  # don't do this
  # serialize :kind, ActiveRecord::Coders::Hstore

  # do this
  store_accessor :kind

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top