I've started learning Ruby last week, and I've started learning Rails today, so bear with me. I see that Rails come with generators that allow you to generate models/controllers or even model+controller+views bundle as 'scaffold'. This is what I am interested in.
However, I have a question. How do I set database options of the column?
eg. To generate a users table I would do:
rails g scaffold users uuid:binary name:string email:string password:binary registered_on:date number:integer default:string
Now what if I'm integrity freak and am not happy by having validation just in model/controller, but want to do database level limitations as well.
What if I want email
to be 50 characters max, and number
to Auto-Increment and neither of all fields is allowed to be NULL and default
field must have a default of 'foo'. Is there any way to pass these requirements to generator command?
I know its possible to set these options in .rb file that is used in rake db:migrate, however it would be easier to just pass values in with 1 command.
To generate a fully working scaffold for a new object, including model, controller, views, assets, and tests, use the rails g scaffold command. Then you can run rake db:migrate to set up the database table. Then you can visit http://localhost:3000/widgets and you'll see a fully functional CRUD scaffold.
Rails Generate Resource You enter the name of the resource you want to create along with the table column names and types. You can even assign foreign keys in this line of code so that you save time. Generating a resource does everything generating a model does, but it also creates a resource in the routes.
Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
At least some things are available, like string length, but not sure about the others.
rails g scaffold users email:string{50}
Use type modifiers between curly braces, example:
rails generate migration AddDetailsToProducts price:decimal{5,2}
More info: migrations
db/migrate
.After you are done customizing the fields, don't forget to do a rake db:migrate
.
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