简体   繁体   中英

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.

至少有一些东西是可用的,比如字符串长度,但不确定其他东西。

rails g scaffold users email:string{50}
  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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM