Rails 3: Difference between revisions
Jump to navigation
Jump to search
| Line 32: | Line 32: | ||
<pre> | <pre> | ||
class CreateArticles < ActiveRecord::Migration | class CreateArticles < ActiveRecord::Migration | ||
def self.up | |||
create_table :articles do |t| | |||
t.timestamps | |||
end | |||
end | |||
def self.down | |||
drop_table :articles | |||
end | |||
end | end | ||
</pre> | </pre> | ||
Revision as of 23:49, 9 June 2011
Application Setup
- create project with
rails new my_project rails -d mysql new my_project # if you don't want the default sqlite3
- add gem dependencies to
Gemfileat the root level - update
config/application.rbto load needed dependencies and update defaults - double-check
/config/initializersand/config/environments - edit
config/database.ymlto 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 Table
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.timestamps
end
end
def self.down
drop_table :articles
end
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 => 1
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 models, views, 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"