Rails generate model - field constraints?

1k Views Asked by At

I know that I can generate a model and set a constraint such as uniq by doing "rails generate model field1:string:uniq", for example. Is there a way I can set a "not null" constraint?

1

There are 1 best solutions below

0
Marcelo Ribeiro On

I don't think you can do that while running the generator. Have you considered changing the migration file after your model is generated?

Migration files are inside db/migrations, and you could make a field as not nullable by adding a few parameters to your migration line, before running rake db:migrate.

Suppose you have a column named category_id:

t.integer :category_id, null: false, default: 0

This would create the field in the database in a not null format.