Rails 3 Basics: Difference between revisions

From Wiki
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 3: Line 3:
<pre>
<pre>
rails new my_project
rails new my_project
rails -d mysql new my_project # if you don't want the default sqlite3
rails new my_project -d mysql  # if you don't want the default sqlite3
</pre>
</pre>
* add gem dependencies to <code>Gemfile</code> at the root level
* add gem dependencies to <code>Gemfile</code> at the root level, then run "<code>bundle install</code>" as root to install required gems.
* update <code>config/application.rb</code> to load needed dependencies and update defaults
* update <code>config/application.rb</code> to load needed dependencies and update defaults
* double-check <code>/config/initializers</code> and <code>/config/environments</code>
* double-check <code>/config/initializers</code> and <code>/config/environments</code>
Line 112: Line 112:
To create a link to this route (old way):
To create a link to this route (old way):
<pre>
<pre>
link_to "Products", :controller => "products", :action => "show", :id => 1
link_to "Products", :controller => "products", :action => "show", :id => 8
</pre>
</pre>



Latest revision as of 19:06, 6 December 2011

Application Setup

  • create project with
rails new my_project
rails new my_project -d mysql  # if you don't want the default sqlite3
  • add gem dependencies to Gemfile at the root level, then run "bundle install" as root to install required gems.
  • update config/application.rb to load needed dependencies and update defaults
  • double-check /config/initializers and /config/environments
  • edit config/database.yml to connect to your database

Notes

Files in lib/ are not automatically loaded, so you need to require them.

In config/environments/development.rb, set

config.action_mailer.perform_deliveries = false

No delivery attempt is performed, but you can still see the mail in the log file to check it looks good

Database Setup

  • create database with
rake db:create

Create a table and its controller

rails generate model Article

Edit db/migrate/20100223220648_create_articles.rb to look like this:

class CreateArticles < ActiveRecord::Migration
    def self.up 
        create_table :articles do |t|
            t.string :title
            t.text :body
            t.datetime :published_at
            t.timestamps
        end
    end
    def self.down
        drop_table :articles
    end
end

To create/update the table:

rake db:migrate

To generate the controller:

rails generate controller articles

Make a scaffold

To make a scaffold for the table to allow easy create/update/delete in development:

rails generate scaffold Article title:string body:text published_at:datetime --skip-migration

WARNING: As you develop your application, you will eventually replace most or even all of the code that the scaffold generates in the controller.

Update table and scaffold

To modify the table, generate a custom migration:

rails generate migration add_excerpt_and_location_to_articles excerpt:string location:string

creates this migration file db/migrate/20100223232337_add_excerpt_and_location_to_articles.rb:

class AddExcerptAndLocationToArticles < ActiveRecord::Migration
    def self.up
        add_column :articles, :excerpt, :string
        add_column :articles, :location, :string
    end
    def self.down
        remove_column :articles,
        :excerpt remove_column :articles, :location
    end
end

Run rake db:migrate again to update the database.

Now update the scaffold:

rails generate scaffold Article title:string location:string excerpt:string body:text published_at:datetime --skip-migration

Add validations to the model

Edit app/models/article.rb:

class Article < ActiveRecord::Base
    validates :title, :presence => true
    validates :body, :presence => true
end

Other rails commands

rails console
rails dbconsole
rails server
rails runner

Routing

Configured in config/routes.rb

match 'products/:id' => 'products#show'

The url http://localhost:3000/products/8 will be mapped to the show action of the products controller with params[:id] set to 8

To create a link to this route (old way):

link_to "Products", :controller => "products", :action => "show", :id => 8

To restrict the HTTP method, use get or post instead of match:

get 'products/:id' => 'products#show'

To redirect:

match "/foo", :to => redirect("/bar")

Logging

Use these in views and controllers to send timestamped messages to the log.

logger.debug "debug message"
logger.info "info message"
logger.warn "something bad"
logger.error "something broke"
logger.fatal "application dead"

In Models, you need something like this:

ActiveRecord::Base.logger.debug