The Rails 5 Way08 May 2017
I started reading The Rails 5 Way recently and decided I’m going to post little snippets I want to use in the future. Hello, future me. You’re welcome. These are either:
- Stuff I’ve looked up a thousand times because I keep forgetting the syntax
- New stuff that I want to use
Loading gems from GitHub
If the gem source repository is hosted on GitHub and is public, you can use the
Generator Default Settings
Rails generator scripts make certain assumptions about your tool chain. Setting the correct values here means having to type fewer parameters on the command line. For instance, to use RSpec without fixtures and Haml as the template engine, our settings would look like the following:
It’s possible to supply a block to
console to be evaluated when the Rails environment is loaded via the terminal. This enables you to set console-specific configurations. I like saving some typing with helper methods like this one.
Watch Rails Log Files
Named Routes in the Console
You can test named routes in the console directly using the special
Limiting Routes Generated
It’s possible to add
:only options to the call to
resources in order to limit the routes generated.
Custom Flash Types
New to Rails 4 is the capability to register your own flash types by using the new
ActionController::Flash.add_flash_types macro style method.
When a flash type is registered, a special flash accessor, similar to alert and notice, becomes available to be used with redirect_to.
It’s particularly important to take care in specifying conditions that include boolean values. Databases have various different ways of representing boolean values in columns. Some have native boolean datatypes, and others use a single character, often
F (or even
N). Rails will transparently handle the data conversion issues for you if you pass a Ruby boolean object as your parameter:
Active Record UUID
UUIDs are becoming a popular alternative to auto-incrementing integer primary keys. (Not supported in all databases, though.)
Rails Migration Generator Magic
If the migration name is of the form “AddXXXToYYY” or “RemoveXXXFromYYY” and is followed by a list of column names and types then a migration containing the appropriate
remove_column statements will be created.
If you’d like to add an index on the new column, you can do that as well:
The migration generator will produce join tables if “JoinTable” is part of the name.
will produce the following migration:
It’s actually super common to forget to add something to a migration. Rails gives you
rails db:migrate:redo as a convenient way to rollback and re-migrate in one command.
db:reset and db:setup
db:setup creates the database for the current environment, loads the schema from
db/schema.rb, then loads the seed data. It’s used when you’re setting up an existing project for the first time on a development workstation. The similar
db:reset task does the same thing except that it drops and recreates the database first.