如何使用Hstore的PostgreSQL在Sinatra简单的应用程序中工作?

时间:2014-03-27 13:23:23

标签: ruby postgresql sinatra hstore sinatra-activerecord

我试图让hstore在Postgre数据库中使用sinatra 1.4.4和sinatra-activerecord(1.5.0)

我使用宝石

处理ruby-1.9.3-p392
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

这些是我的迁移:


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

在模型engine_parameter.rb中使用这些行:

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

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

然后在控制台中我想用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'

然后我再试一次:

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'

我没有找到问题的答案。最接近的是:https://gist.github.com/bru/3258069,但还不够。

有些事我做错了,却无法找到。

1 个答案:

答案 0 :(得分:0)

好的,我在问到这个问题后不久就找到了答案。

使用新的activerecord,即使是在sinatra上,你也必须把这个

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