alias | defined? | FILE | not | then |
and | do | for | or | true |
BEGIN | else | if | redo | undef |
begin | elsif | in | rescue | unless |
break | END | LINE | retry | until |
case | end | module | return | when |
class | ensure | next | self | while |
def | false | nil | super | yield |
rails new name
Creates a new Ruby on Rails application with the given name.
rails new my_app --database=postgresql
Generate a new Rails app w/ Postgres support
rails generate scaffold name attribute:type
The scaffold command generates all the common things needed for a new resource. This includes controllers, models and views.
rails generate controller name
Creates a new controller and its respective views with the given name here.
rails generate model name attribute:type
Creates a new model with the given name here and its respective migration with attributes mentioned.
rails server
Launches a small web server named WEBrick which comes bundled with Ruby on port 3000
rails console
The console command lets you interact with your Rails application from the command line.
rake db:create
Creates the database for the current environment
rake db:create:all
Creates the databases for all environments
rake db:drop
Drops the database for the current environment
rake db:drop:all
Drops the databases for all environments
rake db:migrate
Runs migrations for the current environment that have not run yet
rake db:rollback
Rolls back the last migration
rake db:seed
(only) runs the db/seed.rb file
rake db:migrate:redo
Runs (db:migrate:down db:migrate:up) or (db:rollback db:migrate) depending on the specified migration
rake db:migrate:reset
Runs db:drop db:create db:migrate
rake tmp:clear
Clears session, cache, and socket files
rake assets:precompile
Compile all the assets named in config.assets.precompile
bundle install
Install the current environment's gems to the system
bundle exec
Run the command in context of the bundle
bundle clean
Cleans up unused gems in your bundler directory
bundle config
Retrieve or set a configuration value
bundle console
Opens an IRB session with the bundle pre-loaded
bundle init
Generates a Gemfile into the current working directory
bundle update
Update the current environment
bundle show
Shows all gems that are part of the bundle, or the path to a given gem
# config/routes.rb
get 'welcome' => 'pages#home'
# config/routes.rb
get 'images/show'
# The above is the same as:
get 'images/show', :to 'images#show'
get 'images/show' => 'images#show'
# config/routes.rb
resources :images
HTTP Verb | Path | Controller#Action | Used for |
---|---|---|---|
GET | /images | images#index | display a list of all images |
GET | /images_new | images#new | return an HTML form for creating a new image |
POST | /images | images#create | create a new image |
GET | /images/:id | images#show | display a specific image |
GET | /images/:id/edit | images#edit | return an HTML form for editing a image |
PATCH/PUT | /images/:id | images#update | update a specific image |
DELETE | /images/:id | images#destroy | delete a specific image |
# config/routes.rb
resources :images, :only => [:index]
# On the flip side, you can create a resource with exceptions
resources :images, :except => [:new, :create, :edit, :update, :show, :destroy]
# config/routes.rb
# If there's a file called 'about.html.erb' in 'app/views/images', this file will be
# automatically rendered when you call localhost:3000/images/about
get 'images/about', to: 'images#about'
Generate a new controller
Note: Name controllers in Pascal case and pluralize
rails g controller Images
Generate a new controller with default actions, routes and views
rails g controller Images index show
Generate a model and create a migration for the table
Note: Name models in Pascal case and singular
rails g model Image
Generate a model and create a migration with table columns
rails g model Image path:string caption:text
The migration automatically created for the above command:
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :path
t.text :caption
t.timestamps null: false
end
end
end
:boolean
:date
:datetime
:decimal
:float
:integer
:primary_key
:references
:string
:text
:time
:timestamp
When the name of the migration follows the format AddXXXToYYY followed by a list of columns, it will add those columns to the existing table
rails g migration AddDateTakenToImages date_taken:datetime
The above creates the following migration:
class AddDateTakenToImages < ActiveRecord::Migration[5.0]
def change
add_column :images, :date_taken, :datetime
end
end
You can also add a new column to a table with an index
rails g migration AddDateTakenToImages date_taken:datetime:index
The above command generates the following migration:
class AddDateTakenToImages < ActiveRecord::Migration[5.0]
def change
add_column :images, :date_taken, :datetime
add_index :images, :date_taken
end
end
The opposite goes for migration names following the format: RemoveXXXFromYYY
rails g migration RemoveDateTakenFromImages date_taken:datetime
The above generates the following migration:
class RemoveDateTakenFromImages < ActiveRecord::Migration[5.0]
def change
remove_column :images, :date_taken, :datetime
end
end
Scaffolding is great for prototype applications:
rails g scaffold Image path:string caption:text
rake db:migrate
Creating a path helper for a route
# Creating a path helper for a route
get '/images/:id', to: 'images#show', as: 'image'
# app/controllers/images_controller.rb
@image = Image.find(17)
# View for the action
<%= link_to 'Image Record', image_path(@image) %>
Path helpers are automatically created when specifying a resource in config/routes.rb
# config/routes.rb
resources :images
HTTP Verb | Path | Controller#Action | Named Helper |
---|---|---|---|
GET | /images | images#index | images_path |
GET | /images/new | images#new | new_image_path |
POST | /images | images#create | images_path |
GET | /images/:id | images#show | image_path(:id) |
GET | /images/:id/edit | images#edit | edit_image_path(:id) |
PATCH/PUT | /images/:id | images#update | image_path(:id) |
DELETE | /images/:id | images#destroy | image_path(:id) |
Access images in the app/assets/images directory like this:
<%= image_tag "rails.png" %>
Within views, link to JavaScript and CSS assets
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<!-- Filenames are fingerprinted for cache busting -->
<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" />
<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
Bind a form to a model for creating/updating a resource
Use this method if you're using strong params to protect against mass assignment
# app/controllers/images_controller.rb
def new
@image = Image.new
end
# ERB view
<%= form_for @image, url: {action: "create"}, html: {class: "nifty_form"} do |f| %>
<%= f.text_field :path %>
<%= f.text_area :caption, size: "60x12" %>
<%= f.submit "Create" %>
<% end %>
<!-- HTML output -->
<form accept-charset="UTF-8" action="/images/create" method="post" class="nifty_form">
<input id="images_path" name="image[path]" type="text" />
<textarea id="images_caption" name="image[caption]" cols="60" rows="12"></textarea>
<input name="commit" type="submit" value="Create" />
</form>
<%= form_tag("/search", method: "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
<form accept-charset="UTF-8" action="/search" method="get">
<input name="utf8" type="hidden" value="✓" />
<label for="q">Search for:</label>
<input id="q" name="q" type="text" />
<input name="commit" type="submit" value="Search" />
</form>
When you create a Web site or Web application with RoR, you should make sure that you input data in a form that Rails recognizes and can use.
- validates_acceptance_of
- validates_inclusion_of
- validates_associated
- validates_length_of
- validates_confirmation_of
- validates_numericality_of
- validates_each
- validates_presence_of
- validates_exclusion_of
- validates_size_of
- validates_format_of
- validates_uniqueness_of
When you want to travel through a database you created with RoR, using iterators is helpful:
Iterator/Method | Result |
---|---|
[1, 2, 3].each { } | [1, 2, 3] |
[1, nil, nil, 2, 3, nil].compact { } | [1, 2, 3] |
[1, 2, 3].delete_if { | x |
[1, 2, 3].collect { | x |
[1, 2, 3].find_all { | x |
[1, 2, 3].reject { | x |
[2, 5, 1, 0, 7].sort | [0, 1, 2, 5, 7] |
[2, 5, 1, 0, 7].max | 7 |
[1, [2, 3]].flatten | [1, 2, 3] |
[1, 2, 3].empty? | false |
[].empty? | true |
[0, 5, 9].length | 3 |
[1, 2, 3].include?(2) | true |
[1, 2, 3].include?(16) | false |
[1, 2, 3].reverse | [3, 2, 1] |