Rails generate model: be specific

Ariejan de vroomPosted by Ariejan de Vroom on 27-11-2015

Rails can generate a lot of things for you. Personally I use generate model often to quickly setup a new model, including test files and a database migration. In its simplest form it looks like this:

rails generate product

This will get you started with a naked Product model. To make things easier, you can also supply attribute names:

rails generate product name description:text 

Optionally, you can tell the generator what type of attribute you want. You can choose from the same types as you’d normally use in your migration:

Now, that’s not where it ends. Here are some more useful tricks:


You can specify that your model references another. Our Product might belong_to a Category.

rails generate product category:references

This generates the category_id attribute automatically. In some cases you might want to use a polymorphic relation instead, no problem:

rails generate product supplier:references{polymorphic}


For string, text, integer and binary fields, you can set the limit by supplying it in curly braces:

rails generate product sku:string{12}

For decimal you must supply two values for precision and scale:

rails generate product price:decimal{10,2}

Indices / Indexes

You can also set indices (unique or not) on specific fields as well:

rails generate product name:string:index
rails generate product sku:string{12}:uniq
rails generate product supplier:references{polymorphic}:index

Password digests and tokens

If you want to store password digests using has_secure_password, you can also use the digest type.

rails generate user password:digest

And the same goes for has_secure_token.

rails generate user auth_token:token

That’s it. Happy generating.

This article was originally posted at ariejan.net

Ariejan de vroom

Ariejan de Vroom

Software Engineer • CodeRetreat Facilitator • Ruby, Go and C Programmer • Electronics Apprentice

Bij Kabisa staat privacy hoog in het vaandel. Wij vinden het belangrijk dat er zorgvuldig wordt omgegaan met de data die onze bezoekers achterlaten. Zo zult u op onze website geen tracking-cookies vinden van third-parties zoals Facebook, Hotjar of Hubspot. Er worden alleen cookies geplaatst van Google en Vimeo. Deze worden gebruikt voor analyses, om zo de gebruikerservaring van onze websitebezoekers te kunnen verbeteren. Tevens zorgen deze cookies ervoor dat er relevante advertenties worden getoond. Lees meer over het gebruik van cookies in ons privacy statement.