Ruby on Rails Cheetsheet
- Setup Digital server, Nginx host rails, apache2 host PHPMYADMIN
- Update
gem
:
gem install rubygems-update
update_rubygems
gem update --system
(if not work, try
gem update `gem outdated | cut -d ' ' -f 1`
) - Throw an exception manually :
raise ....
- Handle Photo and Album (kylehuynhphotography.com): click here
- Clear the assets
rake assets:clobber (remove /home/rails/tmp/cache/assets)
rake assets:clean
- Check the error log in kylehuynhphotography.com:
cat /var/log/nginx/access.log
- Validate string field is unique
validates :title, :uniqueness => true
- Validating image url format as png, jpeg or gif
validates :image_url, :format => {
:with => %r{A.(gif|jpg|png)/z}i,
:message => ‘must be a URL for GIF, JPG or PNG image.’
}
- Link to images in css, let’s say you store all of images in the directory :/assets/images/cusdir/image.png
background-image:url(“/assets/nobile/cusdir/image.png”)
- Reset database from rails command :
rake db:reset
- Validating number field compare with number value
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
- For (i=0; i< no; i++) in Ruby :
no.times do |p|
…
end
- Generate model from Rails command :
rails generate scaffold Product
title:string description:text image_url:string price:decimal
Then, rake db:migrate
- Remove scaffold model from Rails command:
rails destroy scaffold Product
- rails generate scaffold Product will create table Products with id as default primary key. In order to ignore primary key automatically creating, passing id: false
create_table :products, id: false do |t|
t.string :name, null: false
end
- Instance variable in ruby class
-
- @@variable_name = “hello world”
- call under def : puts @@variable_name
- In the case that you already created table, create a migration class to modify table by the following:
class AddPkPhotoid < ActiveRecord::Migration
def change
remove_column :photos, :id
add_column :photos, :photo_id, :primary_key
end
end
- Parse json and store it to a string variable
require ‘json’
require ‘open-uri’
@json = JSON.parse(open(“..Flickr api url…”).read)
- Add unique validation for 1 or mutiple column for table
validates_uniqueness_of :photo_id
validates_uniqueness_of :photo_id, :scope => :album_id
- Modifying column for table by Rails command
change_column :set_photos, :setphoto_id, :string
- Generate controller by Rails command:
rails generate controller Say hello goodbye