Rails Generator CLI — 101

1. Model Generators

To create a model, follow this formula:

# db/migrate/20180701032833_create_dogs.rbclass CreateDogs < ActiveRecord::Migration[5.1]
def change
create_table :dogs do |t|
t.string :name
t.string :breed
t.text :bio t.timestamps
end
end
end

2. Migration Generators

Adding Columns

To add an additional column to a table, follow this formula:

# db/migrate/YYYYMMDDHHMMSS_add_year_born_to_dogs.rbclass AddYearBornToDogs< ActiveRecord::Migration[5.1]
def change
add_column :authors, :year_born, :integer
end
end

Adding multiple columns

We can also add multiple columns to the dogs table in a single CLI command like so:

rails g migration add_barks_to_dogs barks_done:integer last_game_played:string --no-test-framework
# db/migrate/YYYYMMDDHHMMSS_add_barks_to_dogs.rbclass AddBarksToDogs< ActiveRecord::Migration[5.1]
def change
add_column :dogs, :barks_done, :integer
add_column :dogs, :last_game_played, :string
end
end

Removing Columns

To remove a column, i.e. the last_game_played column from dogs, we can type in CLI:

rails g migration remove_last_game_played_from_dogs last_game_played:string --no-test-framework
#db/migrate/YYYYMMDDHHMMSS_remove_last_game_played_from_dogs.rbclass RemoveLastGamePlayedFromDogs < ActiveRecord::Migration[5.1]
def change
remove_column :dogs, :last_game_played, :string
end
end

3. Resource Generators

To create a new Model, corresponding database table, controller, and an empty views folder type in:

rails g resource ModelName column_name:datatype column_name2:datatype2 --no-test-framework
rails g resource DogWalker first_name:string dog_id:integer --no-test-framework

4. Datatypes

Thanks to this great stack overflow post, below are the list of almost all the datatypes that Rails supports.

5. Don’t forget to rake:db migrate

After using your generator don’t forget to type on your terminal rake:db migrate.

6. Resources

Still have more questions?. Here are some more in-depth resources if any additional information we might need for successfully using our generators.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store