简体   繁体   中英

Adding a default value to a rails database

I've a Postgresql database created in a rails app and I want to add default values.

I created a migration

class AddCityStateDefaults < ActiveRecord::Migration
  def change
    change_table :addresses do |t|
      t.change_default :city, default: "Los Angeles"
      t.change_default :state, default: "CA"
    end
  end
end

But this results in "---:default: Los Angeles" instead of just "Los Angeles"

Just to be sure, the two columns I'm trying to change are named city and state and they are type character varying. I created the migration via bin/rails generate migration AddCityStateDefaults and then edited the migration. I didn't think I could write the changes in the original creation (I know it can be done, but was more complex for me. I'll get to there eventually.)

I new to this, in fact the first migration I ever tried to create other than minor modifications of an existing one.

Thanks. I know it's a small change in syntax, but it was challenging to get to here.

PS. How should I have done it and is changing it now different?

You should pass just a value, not a hash

class AddCityStateDefaults < ActiveRecord::Migration
  def change
    change_table :addresses do |t|
      t.change_default :city, "Los Angeles"
      t.change_default :state, "CA"
    end
  end
end

http://apidock.com/rails/ActiveRecord/ConnectionAdapters/Table/change_default

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM