Friday, September 24, 2010

Rails Cheat Sheet

Rails file structure notes

* Gemfile - which libraries are to be installed and used, the ‘gem’ collections

   group :development do
     gem "rspec-rails", ">= 2.0.0.beta.22"
   end

* config/routes.rb - when a new view has been added, named routes
   match '/help', :to => 'pages#help' # about_path => '/about', about_url => 'http://localhost:3000/about'
o root :to => 'pages#home' # This code maps the root URL / to /pages/home

* app/controllers/pages_controller.rb - when a new page has been added, Ruby code here
  def help
     @title = "Help"
  end

* app/views/pages/help.html.erb - view

* app/views/layouts/application.html.erb - the master html where to reference header and footer partials
  <%= render 'layouts/header' %> # reference _header.html.erb partial

* public/stylesheets/custom.css - public stylesheets
nav ul li {
list-style-type: disc;
display: inline-block;
padding: 0.2em 0;
}

* public/images/logo.png - where images are stored

* app/views/layouts/_header.html.erb - partials, ie header, footer, CSS


<%= link_to 'Help', help_path %>
# use help_path named route
<%= stylesheet_link_tag 'custom', :media => 'screen' %> # use custom.css

* $ rails generate controller Users new - create a Users controller with action new
   create app/controllers/users_controller.rb
   route get "users/new"

* $ rails generate model User name:string email:string - generate model, same as above, model names are singular and controller names are plural

* spec/controllers/users_controller_spec.rb - tests Users controller
  it "should be successful" do
    get '/signup' response.should be_success
    response.should have_selector('title', :content => "Sign up")
  end

* $ rspec spec/ - run tests

* db/migrate/_create_users.rb - User model (database)
o class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :name 


* $ rake db:migrate - migrate up, applies changes in db/*/*.rb model files and calls self.up to create a file called db/development.sqlite3 

* $ rake db:rollback - tear down, ie. calls self.down 

* $ rails console --sandbox - loads console with read-only access to DB 
   >> foo = User.create(:name => "Foo", :email => "foo@bar.com")
   => #
   >> user.errors.full_messages - display error message for object user in rails console
   => ["Name can't be blank"]
 

* $ tail -f log/development.log - console DB logs
 

* app/models/user.rb - Model attribute validate
  validates :name, :presence => true
 

* $ rails generate migration add_email_uniqueness_index - adding structure to an existing model, which creates db/migrate/_add_email_uniqueness_index.rb

No comments: