Data types
- string
- text
- integer
- float
- decimal
- datetime
- timestamp
- time
- date
- boolean
- references
SQL -> ORM -> Arel
# Common commands
User.where(name: 'Simon')
User.find_by(name: 'Simon')
User.limit(2)
User.order(id: :desc)
# Chaining commands
Post.where(view_count: > 20).limit(5).order(id: :desc)
Code for validations are in the model files.
Errors method: error.full_messages, errors.add()
class User < ActiveRecord::Base
vlidate :penn_email
def penn_email
unless email.include? 'upenn.edu'
errors.add(:email, 'is not a Penn email')
end
end
end
Association
One-to-many association
-
Initialize two tables: A and B
-
Declare association:
foreign key of B
primary key of A
Post:references #foreign key column of Comments
db:migrate
belongs_to :user # add in B.rb model file
has_many :comments, dependent: :destroy # destroy corresponding B elements when related A is deleted
@post = Post.find(1);
@new_comment = @post.comments.build
@new_comment.body = 'Comment for post 1'
@new_comment.save
# OR
@new_comment = @post.comments.create({body: 'Comment for posts'})
# Find all comments belongs to a post
@post = Post.find(1);
@comments = @post.comments
# Find a post that a comment belongs to
@comment = Comment.find(20)
@post = @comment.post
Many-to-many association
# in Course.rb and Students.rb model files
rails g Model Registration Course:references Student:references
has_many :registrations, dependent: :destroy
has_many :students, through: registrations
# in Registration.rb model file
belongs_to :student
belongs_to :course
Forms
<%= form_with url: '/login' do |form| %>
<%= form.label :email %>
<%= form.text_field :email %>
<%= form.submit %>
<% end %>
<%= form_with model: @user do |form| %>
<%= form.label :email %>
<%= form.text_field :email %>
<%= form.submit %>
<% end %>
params.require(:post).permit(:title, :content)
Design forms
- field name, type, label
- is the form associate with a model
- Yes,
form_with model
- No,
form_with url
- Yes,
- What end point does the form send to?
Session and authentication
log in: obtain a cookie
and create a session
log out: ask server to remove the cookie-session
pair
session[:last_order] = "latte"
session[:user] = @user
# destroy a session
reset_session
Sessions controller
class SessionsController < AppllicationController
def new
@user = User.new
end
def create
@user = User.find_by(username: params[:username])
if @user.password == params[:password]
session[:user_id] = @user.id
redirect_to @user
end
end
def destroy
reset_session
redirect_to @user
end
end
class ApplicationController < ActionContoller::Base
helper_method :logged_in?, :current_user
def logged_in?
session[:user_id]
end
def current_user
@current_user ||= User.find(session[:user_id]) if logged_in?
end
def autentacate_user
redirect_to login_path unless logged_in?
end
end