1

我正在尝试使 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 ,但还不够。

我做错了什么,但找不到什么。

4

1 回答 1

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
于 2015-03-19T16:08:56.747 回答