简体   繁体   中英

rails model default value

Here is my model migration

class CreateSwimmingClassschedules < ActiveRecord::Migration
  def change
    create_table :swimming_classschedules do |t|
      t.integer :slot_id
      t.integer :coach_id
      t.integer :level_id , :default => 1
      t.string :note

      t.timestamps
    end
  end
end

I expect after I call

Swimming::Classchedule.create(:coach_id=>8)

It will generate a default level_id in table. But somehow it didn't work. I'm in the dev environment using SQLite.

I added

 :default => 1

after I ran

rake db:migrate

Does it matter? Something I am missing?

Adding that line after you have run your migrations will not make the change.

Your syntax is correct but you will need to run a migration with that addition. Consider making a separate migration file like this:

class ChangeLevelId < ActiveRecord::Migration
  def change
    change_column :swimming_classschedules, :level_id, :integer, :default => 1
  end
end

If you added :default => 1 AFTER you did a rake db:migrate , you will need to do a rake db:rollback and do a remigration of your database. That should do the trick.

Is it Classchedule or Classschedule ?

When I have a problem with my database, I recreate it :

rake db:drop
rake db:create
rake db:migrate

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