Scaffold Generator
It generates:
- Model/migration
- contoller file and implementation
- the entire view folder
- all restful routes
rails new blogDemonstration
cd blogDemonstration/
rails g scaffold Post title:string content:text
rails d scaffold Post
# in routes.rb add the root route
root "posts#index"
Arel
# show query result using gem
rails c
Hirb.enable
Post.all
Post.all.where(title: "test").where(content: "ruby")
Post.all.where("id > 2") # where returns all, return [] when not found
Post.all.find_by(title: "test") # find_by returns the first, return nil when not found
Post.all.find(1) # throw ERROR if not found
Post.all.limit(3) # give the first 3 existing
Post.all.where(title: "test").order(:created_at)
Validation
- define a method in the model file
- check if your desire validation passes
- if not, add the column name as a symbol and the error message to the errors object
- pass the method as a symbol to validate
class User < ActiveRecord::Base
validate :penn_email
def penn_email
unless email.include? 'upenn.edu'
errors.add(:email, 'is not a penn email')
end
end
end
https://guides.rubyonrails.org/active_record_validations.html#custom-validators
One-to-many
rails g scaffold User name:string
rails g scaffold Post title:string content:text user:references
rails db:migrate
# Post.rb model file
belongs_to :user
# User.rb model file
has_many :posts, dependent: :destroy
Many-to-many
Create a third table to seperate a many-to-many to two one-to-many
rails g scaffold Course name:string
rails g scaffold Student name:string
rails g Model Registration Course:references Student:references
# in Registration.rb model file
belongs_to :student
belongs_to :course