This is a reference guide for everything you've learned so far in Rails.
new
commandThis will create a new Rails project in the project_name
folder.
rails new project_name
generate
commandRails generators will automatically create files for you in the correct places.
We most often use the model
and migration
generator. The controller
generator is less useful, as it adds many files you don't need, and it doesn't properly set up routes.
The model generator will automatically create model class files, and their create_table
migration. This is really helpful!
rails generate model ModelName name:string count:integer description:text
ModelName
must be in TitleCase (each word capitalized with no spaces or underscores) or snake_case (all letters lowercase with underscores instead of spaces).
Attributes must specify their type, or it will default to string. The most common data types are:
Migrations are used for modifying the structure of your database. Since the model generator generates a create_table
migration, the migration generator is most commonly used for modifying existing tables, such as adding new columns.
$ rails generate migration MigrationName
Just like ModelName
, MigrationName
must be TitleCase or snake_case.
The migration generator offers several helpful shortcut names, such as AddAuthorToArticles
, which will automatically create a migration for you based on the name. This can be a bit confusing until you get the hang of it, but just remember convention over configuration. Here's an example:
$ rails generate migration AddAuthorToArticles author:string
This will automatically create a migration that adds the author:string
attribute to the articles
table.
Other Options
The migrations generator has many different options. See the Migration section of the Rails Guides for very helpful documentation.
server
commandTo start a Rails server:
$ rails server
You can also use a shorthand command for most Rails commands. This will also start a server:
$ rails s
console
commandThe Rails Console is an incredibly valuable and versatile tool for exploring your Rails app and developing new code.
$ rails console
# OR
$ rails c
Pry makes the Rails console about fifty times better . To use Pry with the Rails Console, make sure you add it to your Gemfile
here:
# Gemfile
group :development, :test do
gem 'pry-rails'
# ... your other gems
end
Be sure to run bundle
every time you change your Gemfile
!
Some useful pry-rails commands:
Routes are used by Rails to define the URLs of your web site, which are like the endpoints of your application's API. When a browser visits an URL that matches one of your routes, Rails will instantiate the matching controller, and invoke the action method specified by the route.
Routes can be specified manually like this:
get 'welcome/index'
get 'welcome/about'
In this case, the WelcomeController
will be instantiated, and the index
or about
method will be invoked.
Generally though, we want to use a RESTful resource.
resources :articles
This means Rails will automatically generate routes for the seven restful routes (not to be confused with the seven deadly sins):
HTTP Verb | Path | Controller#Action | Used for |
---|---|---|---|
GET | /articles | articles#index | display a list of all articles |
GET | /articles/new | articles#new | return an HTML form for creating a new article |
POST | /articles | articles#create | create a new article |
GET | /articles/:id | articles#show | display a specific article |
GET | /articles/:id/edit | articles#edit | return an HTML form for editing a article |
PATCH/PUT | /articles/:id | articles#update | update a specific article |
DELETE | /articles/:id | articles#destroy | delete a specific article |
Each of the Seven Restful Routes corresponds to one of the data actions in CRUD. Here's a list of how they relate!
Further Reading
As always, Rails Guide's has an excellent page about routes, called Routing from the Outside In.
Controllers are the "dispatchers" of the application.
We call the methods in a controller an action method. However, an action method is not a special kind of method, it simply means that there is a route that corresponds to that method. So index
is an action method if there is an index
route.
Like any object instances, you must use @instance_variables
for your variables to be available outside of the method. If you want a view template to be able to access a variable, it must be an instance variable!
The server passes in a list of parameters to your Rails app. Rails allows you to access these params with the params
attribute available to any of your controller methods.
params
contains information about the HTTP request, but it is most often used for forms.
Strong parameters prevent hackers from hacking your web site. This is such a big problem that Rails will prevent you from passing the params
hash directly to model methods!
To use strong parameters, you use the require
and permit
methods on the params
hash.
def article_params
params.require(:article).permit(:title, :text)
end
See the Rails Guide's section on Strong Parameters for more information.
Views are simply HTML templates that also allow you to embed Ruby using ERB.
Because of convention over configuration, you should name your view templates based on the action methods of your controllers. As long as your view template names match the action methods of your controller, Rails will automatically know when to render them.
This means that you usually have at least these four view templates in each controller's views folder.
Why only those four? The other RESTful Routes are redirects. create
and update
both redirect to show
after the method runs. The destroy
method redirects to the index
page after the method runs.
To use Ruby in a view template, you have two tags available to you.
<% just_run_me %>
- Tags without the equal sign will simply run Ruby code, and will ignore the return value<%= output_return_value %>
- Tags using the equal sign will output the return value into the HTML templateThe most common use of ERB in Rails is to output data from models. Here's an example:
<div id="content">
<% @articles.each do |article| %>
<article>
<h1><%= article.title %></h1>
<p><%= article.text %></p>
</article>
<% end %>
</div>
While you are encouraged to put Ruby code in your views, you should do the barest minimum amount of Ruby coding possible to get your desired results. More complex Ruby code should either go in the controller, or in a custom helper method.
Things that are ok to do in a view template
each
form_for
, link_to
, etc.)Example things you should do in the Controller instead of the View
.all
, .find
)params
hashModels are how you interact with your database programmatically. Instead of having to manually write SQL statements for all of your database CRUD, you can instead use basic Ruby objects that Rails uses to represent your database CRUD!
All attributes of your models are read from the database! You do not manually assign attributes to a model through Ruby code. Convention over configuration!
See below about Migrations for more.
All Rails models have a large set of CRUD methods available to you. Here's an example:
# Create
Animal.create name: "Giraffe", description: "Has a realllly long neck."
# Read
giraffe = Animal.find_by name: "Giraffe"
# Update
giraffe.update name: "Baby Giraffe"
# Destroy
giraffe.destroy
Instantiating
.new
- Creates a new instance of a model. This does not change the database, until you call save
..create
- Initializes a new model, and writes it to the database. This is used less often than .new
because you often want to do more to the model before you save to the database.Querying
.find
- Looks up a single model by it's id
. This only works for id
s. It is the most commonly used CRUD method..where
- Similar to find_by
but will return all records that match the statement. The where
method has a lot of options, and is the second most frequently used method..find_by
- Looks for a single model using a hash. (This will match exactly. find_by(name: 'Bil')
will not match "Bilbo").all
- Returns a collection of all records of this model in the database..order
- Sort the results of .all
or .where
by a particular column. You can specify multiple columns..first
- Gets the first record of a table. Generally not very useful unless paired with sorting..find_or_initialize_by
- This method takes a hash like .find_by
but if it doesn't find a matching record in the database, it will instead initialize a new instance of the object with the specified attributes. This is most often used when querying for the existence of Users. You won't use it often, but it's really helpful to know that it's there.#save
- Saves the current model to the database#update
- Takes in a hash of attributes and will update them in the database#destroy
- Deletes the current model from the database (be careful, you can't undo this!)All of these methods and many more can be found in the Rails Guides for the Active Record Query Interface.
Migrations are crucial to understanding how to use databases with Rails, but can also be pretty confusing without experience using databases. It's a Catch-22!
Migrations are used primarily for modifying the structure of your database. Remember that we don't explicitly create attributes for our models, and that the database is the authoritative source of information for our models.
In order to modify the database, we have to create a migration. Migrations are most often used for:
author:string
to articles
table)text
to body
)Migrations are a complex subject, and they have their own dedicated Rails Guide. See the Active Record Migrations guide for much more information about how to use them.
Once you have created migrations, you must activate them. You do that with this command:
$ rake db:migrate
You should never ever change an existing migration after you've commited it to git!!
Why?
Migrations are the authoritative source of structural changes in your database. Once you've saved it into history, you've also commited that structure of your database into history forever.
Here's a simple example of what can go wrong:
Betty has trusted Albert not to change the past, but he created a paradox.
Remember,
You should never ever change an existing migration after you've commited it to git!!
If you need to modify the structure of the database again, make another migration!
Seeds are a simple way of adding default data to your database. During development you will throw away your database over and over again as you modify the structure, or have old data that you were playing around with in the Rails Console, or many other scenarios.
Seeds allow you to create a simple set of default test data.
# seeds.rb
# You usually want to delete all of the data before you seed,
# otherwise you'll end up with duplicate records!
Article.delete_all
# We use create! so an error is raised if the save fails.
# create - returns false if the save fails
# create! - raises an error if the save fails
Article.create! title: "Bruskis Climb Lion's Head", text: "They got to the top!"
Article.create! title: "Delicious Breakfast", text: "Students love Knead"
To activate your seeds, you must run the appropriate rake command.
$ rake db:seed
That's it!