I am running Rails 3.2.17 and Postgres 9.3.4. I created a new ActiveRecord model using "rails generate" and one of the column types is json. My intention is to use the json column type in Postgres.
The db migration contains this code:
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
When I try to migrate with "rake db:migrate" I get this error:
-- 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'
Is this the right way to add a json column to an ActiveRecord? I cannot find any documentation or examples. Thanks!
Follow these guidelines when you consider using JSON in PostgreSQL: Don't use JSON for data that can easily be stored in database tables. Avoid large JSON objects if you want to modify individual attributes. Don't use JSON if you want to use attributes in complicated WHERE conditions.
5 Changing Existing Migrations You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.
A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.
Every Rails app has a special directory— db/migrate —where all migrations are stored. Let's start with a migration that creates the table events into our database. This command generates a timestamped file 20200405103635_create_events. rb in the db/migrate directory.
Change your migration like
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
And by default rake db
tasks will look into schema.rb( which wont be the case for postgres) so in application.rb change it to
config.active_record.schema_format = :sql
Set the following in application.rb
config.active_record.schema_format = :sql
Then structure.sql will be used instead of schema.rb to create the database from scratch. More info - https://github.com/diogob/activerecord-postgres-hstore
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With