Rails 3:在由Postgres支持的ActiveRecord中使用json作为列类型时出现迁移错误

23
我是一名有用的助手,可以为您翻译文本。
我正在运行Rails 3.2.17和Postgres 9.3.4。我使用“rails generate”创建了一个新的ActiveRecord模型,并且其中一列类型是json。我的意图是在Postgres中使用json列类型。
数据库迁移包含以下代码:
class CreateThing < ActiveRecord::Migration
  def change
    create_table :things do |t|
      t.integer :user_id
      t.json :json_data
      t.timestamps
    end
    add_index :things, :user_id
  end
end

当我尝试使用 "rake db:migrate" 进行迁移时,出现以下错误:
-- create_table(:things)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined method `json' for #<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition:0x007fea3d465af8>/Users/../db/migrate/20140425030855_create_things.rb:7:in `block in change'
/Library/Ruby/Gems/2.0.0/gems/activerecord-3.2.17/lib/active_record/connection_adapters/abstract/schema_statements.rb:160:in `create_table'

这是向ActiveRecord添加json列的正确方法吗?我找不到任何文档或示例。谢谢!


4
尝试这样写:t.column :json_data, :json。意思不变,通俗易懂。 - Pavan
3个回答

32

将您的迁移更改为以下内容:

class CreateThing < ActiveRecord::Migration
  def change
    create_table :things do |t|
      t.integer :user_id
      t.column :json_data, :json   # Edited
      t.timestamps
    end
    add_index :things, :user_id
  end
end

默认情况下,rake db任务将查看schema.rb文件(这对于postgres不适用)。因此,在application.rb中更改它:

config.active_record.schema_format = :sql

1

0

我们有一个遗留应用程序,它使用 activerecord-postgres-json 为 Rails 3.2 中的 ActiveRecord 提供 jsonjsonb 类型支持;如果你被卡在低版本的 Rails 上,这可能是一个选项。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接