Can anyone please help with generating Rails models with mandatory fields/columns (i.e. NOT NULL)? For example,
$rails generate model Role name:string <???>
What do I need to specify in order to get the "null: false" constraint as shown below?
class CreateRoles < ActiveRecord::Migration
def change
create_table :roles do |t|
**t.string :name, null: false**
t.timestamps
end
end
end
Thanks heaps in advance
:null => false in a Rails migration tells your database not to accept NULL values. It can be used with :default => 0 to tell your database to use '0' as the default value (a) when NULL or nothing is specified in a query or (b) when creating or updating an object.
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.
To undo a rails generate command, run a rails destroy command. You can then edit the file and run rake db:migrate again. (See how to roll back a Migration file to rollback a specific migration or multiple migrations.)
You can't do that in a generator command. It's quite simple to add null: false
to your migration file though.
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