Skip to content

Instantly share code, notes, and snippets.

View thanhcuong1990's full-sized avatar
🏠
Working from home

Cuong Lam thanhcuong1990

🏠
Working from home
View GitHub Profile
# db/migrate/XXXXXXXXXXXXX_add_authentication_token_to_users.rb
class AddAuthenticationTokenToUsers < ActiveRecord::Migration
def change
add_column :users, :authentication_token, :string
add_index :users, :authentication_token, :unique => true
end
end
@thanhcuong1990
thanhcuong1990 / nested_attributes(2).rb
Created July 25, 2014 17:07
Nested attributes example 2
# /app/models/user.rb
class User < ActiveRecord::Base
has_one :account_setting, :dependent => :destroy
accepts_nested_attributes_for :account_setting
end
# /app/controllers/users_controller.rb
class UsersController < ApplicationController
def new
@thanhcuong1990
thanhcuong1990 / nested_attributes(1).rb
Last active August 29, 2015 14:04
Nested attributes example 1
# /app/models/user.rb
class User < ActiveRecord::Base
has_one :account_setting, :dependent => :destroy
end
# /app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@thanhcuong1990
thanhcuong1990 / posts_controller(14).rb
Created July 25, 2014 15:30
Fantastic filters example 4
# /app/controllers/posts_controller.rb
class PostsController < ApplicationController
def edit
@post = get_post(params[:id])
# ...
end
def update
@post = get_post(params[:id])
# ...
@thanhcuong1990
thanhcuong1990 / posts_controller(13).rb
Created July 25, 2014 15:23
Fantastic filters example 3
# /app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_filter :get_post, :only => [:edit, :update, :destroy]
def edit
# ...
end
def update
# ...
@thanhcuong1990
thanhcuong1990 / posts_controller(12).rb
Created July 25, 2014 15:16
Fantastic filters example 2
# /app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_filter :get_post, :only => [:edit, :update, :destroy]
def get_post
@post = Post.find(params[:id])
end
def edit
# ...
@thanhcuong1990
thanhcuong1990 / posts_controller(11).rb
Created July 25, 2014 15:09
Fantastic filters example 1
# /app/controllers/posts_controller.rb
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
# ...
end
def update
@post = Post.find(params[:id])
# ...
current_user.posts.create(
:title => "This is the title",
:content => "This is the content of post"
)
# /app/controllers/posts_controller.rb
p = Post.new
p.title = "This is the title"
p.content = "This is the content of post"
p.user = current_user
p.save
@thanhcuong1990
thanhcuong1990 / topic(4).rb
Created July 20, 2014 16:13
Scope examples
# /app/models/topic.rb
class Topic < ActiveRecord::Base
scope :trending, lambda { |num = nil| where('started_trending > ?', 1.day.ago).
order('mentions desc').
limit(num) }
# ...
end