Starting with Rails

No Comments

Install Ruby. If you are on Windows, 2.3 seems to have issue as of September 2016, so I would go with 2.2.

Install Rails:
gem install rails –version 5.0.0 –no-ri –no-rdoc

Create a new application:
rails _5.0.0_ new application_name
use –skip-test or -T if you don’t want default test files or want to use a different test framework (Test::Unit is default)

Run the application:
rails s

If you are seeing something like this:

Could not load 'active_record/connection_adapters/sqlite3_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.

You probably have ruby version above 2.2 and you are on Windows. Downgrade to 2.2 or try a different OS.

Create a route for your first action:

verb "url" => "name_of_controller#name_of_action"
get 'movies' => 'movies#index'

Generate/destroy a controller:

rails g controller name_of_controller
rails destroy controller name_of_controller

If you don’t want to use the default framework, add –no-test-framework when generating a controller.

Update your view with something like this:

<ul>
<% @movies.each do |movie| %>

<li> <strong><%= movie.title %></strong> (<%= movie.rating %>) <%= number_to_currency(movie.total_gross) %></li>
<% end %>
<ul>

Create a model

rails generate model NAME [field[:type][:index] field[:type]
rails g model event name:string location:string price:decimal

To generate the whole resource:

rails g resource Resource_name column_name:column_type --no-test-framework

To destroy the resource:

rails destroy resource Resource_name column_name:column_type --no-test-framework

Use any of these DB column types types for your model:

string
text
integer
decimal
float
boolean
binary
date
time
datetime
primary_key
timestamp

To declare foreign key relationship: belongs_to :parent
To reference children in parent model: has_many :children
To cascade deletes: has_many :reviews, dependent: :destroy

To attach parent to child: child.parent = parent
Or, parent.children.new(…)

Run migration:
rails db:migrate
rauks db:migrate:status

Seeds:
Use seeds.rb to create seed records for development
To run: rails db:seed

To look up commands:
rails -T
rails -T db

To Look up routes:
rails routes
In browser: {your_app_base_address}/rails/info/routes

for path/url use route_name_path/route_name_url
In rails command line (rails c):
app.route_name_url
app.route_name_path
app.route_name_path(model)
<%= link_to("Whatever text", route_name_path) %>
Shortcut: <%= link_to("Whatever text", model) %>
Use _path in view templates and _url in controllers as redirects.

Routes with parameters
get ‘route/:id’ => ‘controller#show’, as: ‘some_route_name’
<%= link_to "Whatever text", route_name_path(model) %>
Shortcut: <%= link_to "Whatever text", model %>

Root route
root ‘controller#action’

Submitting Forms
Sample form:

<%= form_for(@movie, @review) do |f| %>
  <p>
    <%= f.label :title %>
    <%= f.text_field :title %>
  </p>
  <% Review::STARS.each do |star| %>
    <%= f.radio_button :stars, star %> <%= star %>
  <% end %>
  <p>
    <%= f.submit %>
  </p>
<% end %>

Updating a model

def update
  @movie = Movie.find(params[:id])
  @movie.update(params[:movie])
end

To allow specific model fields to be updated
params[:movie].permit(:title, :description)

Or (will fail if movie is not submitted)
params.require(:movie).permit(:title)

To allow all fields to be updated:
params.require(:movie).permit!

Working with Active Record
Ordering:
Movie.order(‘released_on’)
Movie.order(‘released_on asc’)
Movie.order(released_on: :asc)

Searching:
Movie.find(2)
Movie.find_by(title: “Iron Man”)
Movie.where(rating: “PG-13”)
Movie.where.not(rating: “PG-13”)
Movie.where.not(rating: [“PG”, “PG-13”])
Movie.where(“total_gross < ?", 50000000) Movie.where("released_on > ?”, Time.now)
Movie.where(“released_on <= ?", Time.now).order("released_on desc") To view SQL use to_sql: Movie.where(rating: "PG-13").to_sql To rollback last migration: rails db:rollback
Assets
To see assets: http://base_url/assets/asset_name
http://localhost:3000/assets/application.js

Validation
Active Record methods on an instance:
e.valid?
e.errors
e.errors[:name]
e.errors.full_messages
movie.errors.full_messages.to_sentence

Validation Examples:
validates :title, :released_on, :duration, presence: true
validates :description, length: { minimum: 25 }
validates :total_gross, numericality: { greater_than_or_equal_to: 0 }

validates :image_file_name, allow_blank: true, format: {
with: /\w+\.(gif|jpg|png)\z/i,
message: “must reference a GIF, JPG, or PNG image”
}
RATINGS = %w(G PG PG-13 R NC-17)
validates :rating, inclusion: { in: RATINGS }
movie.errors.full_messages.to_sentence

Controllers
To run something before each action:
before_action :method_name

Flashes
One time messages.
To set:
flash[:notice] = “Message!”
If in redirect, can do:
redirect_to some_url, alert: “Alert!”
To read in view:
<%= flash[:notice] %>

Custom Flashes with redirects:
Rails only supports :notice and :alert by default for redirects. To add a custom one, add this to your ApplicationController: add_flash_types(:danger)

Gemfile
To set gems for specific environment:
group :development, :test do
gem ‘sqlite3’
end
To install gems excluding a group:
bundle install –without production

Nested resources
resources :parents do
resources :children
end

Categories: Rails, Ruby

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Loading Facebook Comments ...