Skip to content

Instantly share code, notes, and snippets.

@lin
Last active August 29, 2015 14:07
Show Gist options
  • Save lin/fb2134e1787ecf819ba9 to your computer and use it in GitHub Desktop.
Save lin/fb2134e1787ecf819ba9 to your computer and use it in GitHub Desktop.
Cheatsheet for Ruby on Rails
##CRUD##
#create
Human.create
#read
Human.find(2)
Human.first
Human.last
human.name
#update
human.name("albert")
human.save
#delete
human.destroy
##Model##
class Human < ActiveRecord::base
validates_presence_of :name
validates_uniqueness_of :name
validates :name, presence: true, uniqueness: true
has_many: titles
end
class Title < ActiveRecord::Base
belongs_to :human, foreign_key: :human_id, dependent: :destroy
end
# convention over configuration
# it will render show.html.erb
class ProductController < ApplicationController
def show
@product = Product.find(params[:id])
end
end
# it will render status.html.erb
class ProductController < ApplicationController
def show
@product = Product.find(1)
@products = Tweet.includes(:thumbnail).recent
render action: "status"
end
end
# params
?id=123&status[today]=good
#session hash
#flash hash
#params hash
#redirect_to
before_action get_product, only: [:edit, :delete]
#Scoping allows you to specify commonly-used queries
#which can be referenced as method calls on the association objects or models.
class Human < ActiveRecord::Base
scope :smart, where(smart: true)
scope :young, where("age < 25")
scope :recent, where("create_at desc").limit(3)
end
#reading no need self, setting need self
class Human < ActiveRecord::Base
before_save :become_smart
def become_smart
self.smart = true if age > 25
end
end
#before after events
before_save
after_save
before_validation
after_validation
before_create
after_create
before_destroy
after_destroy
#has_one
humans = Human.includes(:pet).all
$rails new ProjectName
$rails generate / g
$rails console / c
$rails server / s
$rails dbconsole / db
$rails g scaffold Human name:string bio:text age:integer
string text boolean decimal float binary date time datetime
####
$rails db:migrate
$rails db:rollback
$rails db:schema:dump
$rails db:setup
$bundle install
# app/config/routes.rb
get '/new_product' => 'product#new'
get '/all' => 'products#index' as all_products
<%= link_to "all products", all_products_path %>
get '/all' => redirect('/products')
get '/filter_by/:category' => 'products:index'
#root
root to: "tweets#index"
root_path
hash = { 'color' => 'green', 'number' => 5 } # string as keys
hash['color'] #=> 'green'
hash = { defcon: 3, action: true } # symbol as keys
hash['defcon'] #=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment