Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - generate Scaffold with Table Options

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.

like image 792
if __name__ is None Avatar asked Feb 14 '13 23:02

if __name__ is None


People also ask

How do you generate scaffold in rails?

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.

What does rails generate resource do?

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.

What is scaffolding in Ruby on rails?

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.


2 Answers

At least some things are available, like string length, but not sure about the others.

rails g scaffold users email:string{50}
like image 128
Dave Newton Avatar answered Oct 26 '22 13:10

Dave Newton


  1. Use type modifiers between curly braces, example:

    rails generate migration AddDetailsToProducts price:decimal{5,2} 
    

    More info: migrations

  2. Use scaffold and obtain generic migration files. And, as you mentioned, do the customizations in there. This files are found in db/migrate.

After you are done customizing the fields, don't forget to do a rake db:migrate.

like image 21
givanse Avatar answered Oct 26 '22 13:10

givanse