Anda di halaman 1dari 7

Ruby on Rails 3 Cheat Sheet

Naming Conventions: Variables: all lowercase and words separated by underscores (order_status) Classes and Modules: each word in a phrase is capitalized (LineItem) Database: all lowercase words separated by underscores. Table names are plural (line_items) Files: all lowercase with underscores Model Naming: Table File Class Controller Naming: URL File Class Method Layout View Naming: URL File Helper File Class Name Order TaxAgency Batch Diagnosis LineItem Person Datum Quantity http:///store/list app/views/store/list.html.erb (or .builder or .rjs) module StoreHelper app/helpers/store_helper.rb Table Name Orders Tax_agencies Batches Diagnoses Line_items People Data quantities http:///store/list app/controllers/store_controller.rb StoreController list app/views/layouts/store.html.erb line_items app/models/line_item.rb LineItem

@2012, Technology Three (www.technologythree.com)

Ruby on Rails 3 Cheat Sheet


Versions $ ruby v $ rails v Help $ rails h Gems $ gem list # List of Installed Gems rake gems:install Installs all required gems for this application. gem install GemName Installs the specified gem in to your machine. gem uninstall GemName Uninstalls the specified gem from your machine. gem server present a web page at http://localhost:8808/ with info about installed gems. Bundler $ bundle install Routes $ rake routes # Lists all routes Rails $ rails h # Shows commands available # Start Rails Server # Starts Rails in Test mode # Starts Rails in Production mode # Generate new Controller # Generates new Model # Generates new Scaffold $ rails new APP_NAME # creates new Rails App $ rails server/s $ rails server e test $ rails server e development # Starts Rails in Development mode $ rails server e production # Install Gems and Dependencies # Rails Help # Shows Ruby Version # Shows Rails Version

$ rails generate/g controller CONTROLLER_NAME

$ rails generate/g model NAME [field:type field:type] $ rails generate/g scaffold NAME [field:type field:type] $ rails generate mailer NAME [method method] $ rails destroy controller $ rails destroy model $ rails destroy scaffold $ rails destroy migration

$ rails generate/g migration NAME [field:type field:type]# Generates new Migration # Stubs out a new mailer & views # Undo last controller code generated with generate # Undo last model code generated with generate # Undo last scaffold code generated with generate # Undo last migration code generated with generate # Runs ruby code in the specified file

$ rails destroy mailer # Undo last mailer code generated with generate $ rails runner script/file_name.rb

@2012, Technology Three (www.technologythree.com)

Ruby on Rails 3 Cheat Sheet


Rake $ rake tasks # Full list of tasks $ rake describe task # Complete description of specific task $ rake doc:app $ rake stats Rake Database $ rake db:migrate # Run the migration scripts $ rake db:migrate Version=20110514000009 # Run a particular version of script $ rake db:migrate:redo STEP=4 # Redo one or more migrations $ rake db:rollback # Roll back the database # Dry Run for Database setup $ rake trace dry-run db:setup RAILS_ENV rake db:drop Drops the database for the current RAILS_ENV rake db:reset Drops and recreates the database from db/schema.rb for the current environment. rake db:rollback This will run the down method from the latest migration. rake db:schema:dump Create a db/schema.rb file that can be portably used against any DB supported by AR rake doc:app Build the RDOC HTML Files rake db:sessions:create Creates a sessions migration for use with CGI::Session::ActiveRecordStore Rake Testing $ rake test # Runs all unit, functional and integration tests # Benchmark the performance tests # Runs all the functional tests from test/functional # Runs all the integration tests from test/integration # Run all the plugin tests from vendor/plugins/*/**/test # Profile the performance tests # Tests recent changes # Runs tests which are uncommitted in Subversion # Runs all the unit tests from test/unit $ rake test:benchmark $ rake test:functionals $ rake test:integration $ rake test:plugins $ rake test:profile $ rake test:recent $ rake test:units # Generates programmer documentation under doc/app # Code stats

rake db:create Create the database defined in config/database.yml for the current

$ rake test:uncommitted

$ rake tmp:clear Clear session, cache, and socket files from tmp/

@2012, Technology Three (www.technologythree.com)

Ruby on Rails 3 Cheat Sheet


Rake Test Database $ rake db:test:clone database schema $ rake db:test:clone_structure development structure $ rake db:test:load # Recreate the test database from the current schema.rb # Check for pending migrations and load the test schema $ rake db:test:prepare # Recreate the test databases from the # Recreate the test database from the current environments

$ rake db:test:purge # Empty the test database. rake log:clear Truncates all *.log files in log/ to zero bytes rake rails:freeze:gems Lock this application to the current gems (by unpacking them into vendor/rails) New Project $ rails new APP_NAME d mysql $ cd APP_NAME $ bundle install $ rake db:create $ rails server Rails console $ rails console $ irb Sqlite3 database $ sqlite3 db/development .schema SELECT * FROM users

@2012, Technology Three (www.technologythree.com)

Ruby on Rails 3 Cheat Sheet

Debugging Rails Applications


To inspect the contents of a variable: <%= debug @post %> <%= simple_format @post.to_yaml %> <%= [1, 2, 3, 4, 5].inspect %>

Routing
URL: http://www.example.com/controller/action/id resources :photos creates 7 different routes in your application, all mapping to the Photos controller: Verb GET GET POST GET GET PUT DELETE Path /photos /photos/new /photos /photos/:id /photos/:id/edit /photos/:id /photos/:id Action index new create show edit update destroy Helper photos_path new_photo_path photos_path photo_path(id) edit_photo_path(id) photo_path(id) photo_path(id) used for display a list of all photos return an HTML form for creating a new photo create a new photo display a specific photo return an HTML form for editing a photo update a specific photo delete a specific photo

Creating New Record Save() a_user = User.new a_user.name = Joe a_user.email = joe@example.com a_user.save Create() a_user = User.create ( :name => Joe, :email => joe@example.com ) Create() both instantiates the model object and stores it into the database

@2012, Technology Three (www.technologythree.com)

Ruby on Rails 3 Cheat Sheet


Finding Records a_user = User.find(7) user = User.find_by_name(Joe) users = User.find_all_by_name(Joe) users = User.find_all_by_name_and_email(Joe, joe@example.com) user = User.find_or_initialize_by_user_id(user.id) user = User.find_or_create_by_email(joe@example.com) user = User.find_by_sql(select * from users where email = joe@example.com )

Where clause: user = User.where(name = :name and email = :email, {:name => params[:name], :email => params[:email]}) user = User.where(name like ?, params[:name] + %) users = User.where(name like ?, params[:name] + %).order(id desc) users = User.where(name like ?, params[:name] + %).order(id desc).limit(10) users = User.where(name like ?, params[:name] + %).order(id desc).limit(10).offset(5) user = User.select(name, email).where(name like ?, params[:name] + %)

Column Statistics average = Order.average(:amount) max = Order.maximum(:amount) min = Order.minimum(:amount) total = Order.sum(:amount) number = Order.count orders = Order.where(amount > 10).minimum(:amount)

Named Scopes class Order < ActiveRecord::Base scope :last_n_days, lambda { |days| where(updated < ?, days) } scope :checks, where(:pay_type => :check) end orders = Order.checks.last_n_days(7)

@2012, Technology Three (www.technologythree.com)

Ruby on Rails 3 Cheat Sheet


Updating Existing Records order = Order.find(23) order.name = fred order.save order = Order.find(23) order.update_attribute( :name => fred ) order = Order.find(23) order.update_attributes( :name => fred, :email => fred@example.com )

Deleting Records Order.delete(23) User.delete( [2,5,7,9] ) Product.delete_all( [price > ?, @sale_price ] )

Sequence of Active Record Callbacks

@2012, Technology Three (www.technologythree.com)

Anda mungkin juga menyukai