Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Rails models with mandatory/required fields (i.e not null) from command line

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

like image 969
Roobie Avatar asked Mar 26 '14 12:03

Roobie


People also ask

What is null false in rails migration?

: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.

Which command is true to rollback migration in Rails?

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.

How do you undo a command in rails?

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.)


1 Answers

You can't do that in a generator command. It's quite simple to add null: false to your migration file though.

like image 185
Justus Eapen Avatar answered Oct 25 '22 13:10

Justus Eapen