Rails Guide
Rails Guide
I created this guide as a quick reference for when you are working on your
projects, so you can quickly find what you need & keep going.
MVC Architecture
Full
Letter Description
Name
Migrations
System to update your database schema.
Example 1:
Example 2:
Example 3:
Types of values:
Run migrations:
rake db:migrate
Migration Formats:
Routes
Is the part of Rails that knows how to handle URLs & match them to a
controller.
root "pages#index"
Listing Routes:
rake routes
Scaffolding
Create MVC files, migrations & testing templates.
Example:
ERB
Embbeded Ruby. Allows you to have Ruby code inside HTML.
Loop:
Links:
Validations
Allow you do define what data is valid & what is not valid.
Example:
Format:
validates :legacy_code,
format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" }
Inclusion:
Length:
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :registration_number, length: { is: 6 }
Numericality:
Custom Validation
With validation class:
validate :expiration_date_cannot_be_in_the_past
def expiration_date_cannot_be_in_the_past
if expiration_date.present? && expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past")
end
end
Conditional Validation
class Order < ApplicationRecord
validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
ActiveRecord
Query the database, update & delete data.
Query:
User.all
User.first
User.find_by(email: "[email protected]")
User.where("id > ?", params[:min_id])
Updating:
# Update attributes
@user.name = "John"
# Save changes
@user.save
Example:
Model - User
Table - user
Controller - UsersController
Views Folder - users
Heroku Deploy
When you are ready to deploy your application to heroku you will need to
make sure you have created an account & installed the heroku CLI as per the
instructions.
Login:
heroku login
heroku create
Push changes:
heroku logs
Run migrations:
Also make sure that you have the pg gem on your Gemfile & that
config/database.yml is setup to use postgres in production.
You also want to use postgres locally if possible to avoid any incompatible
changes.
Controller Actions
Share data with views via instance variables.
Example:
def index
@users = Users.all
end
def upvote
redirect_to action: 'index'
end
Layouts
If you want to create a menu or have some elements that show on all of the
pages of your site then you need to use layouts.
It's just a regular view file that you can edit & customize to your needs.
Associations
3 types:
One-to-One
One-to-Many
Many-to-Many
Example:
Then:
rake db:migrate
u = User.first
u.posts