迁移后的 Rails 4“未定义方法`访问器'”

IAm*_*NaN 5 postgresql activerecord hstore ruby-on-rails-4

我的 Rails 4.1.5 应用程序在 Ruby 2.1 上,并且使用 postgresql 和 hstore for store_accessor。从一个新的数据库开始:

rake db:migrate; rake db:seed
Run Code Online (Sandbox Code Playgroud)

...一切正常。

再次回滚和前进,这就是问题开始的地方:

rake db:migrate VERSION=0; rake db:migrate; rake db:seed
Run Code Online (Sandbox Code Playgroud)

如果我尝试访问它的任何“属性”,模型会报告“未定义的方法访问器”。

undefined method `accessor' for #<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::Identity:0xyaddayadda>
Run Code Online (Sandbox Code Playgroud)

该模型将 store_accessor 与 postrgesql 的 hstore 结合使用。模型定义如下:

class Foo < ActiveRecord::Base
  ...
  store_accessor :properties, :color, :material, :brand
  ...
end
Run Code Online (Sandbox Code Playgroud)

迁移定义如下:

class CreateFoos < ActiveRecord::Migration
  def change
    enable_extension "hstore"
    create_table :foos do |t|
      t.hstore      :properties

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

为了使问题消失,我可以在重新创建数据库之前完全炸掉它:

rake db:migrate VERSION=0; rake db:drop:all; rake db:create; rake db:migrate; rake db:seed
Run Code Online (Sandbox Code Playgroud)

这样做意味着每次都停止和重新启动测试和开发环境,这很麻烦。

我尝试添加另一个启用/禁用 hstore 的迁移:

class AddHstore < ActiveRecord::Migration
  def up
    enable_extension :hstore
  end
  def down
    disable_extension :hstore
  end
end
Run Code Online (Sandbox Code Playgroud)

这在 Foo 迁移之前运行。

我怀疑这是 posgresql ActiveRecord 连接器的问题。我可能用错了这个,所以我想把它从你们那里反弹回来。

小智 0

这也可能是由于我们作为 store_accessor 放置的字段不存在于数据库中而导致的。运行迁移确保该字段存在,这为我解决了错误。