Ruby On Rails: An Introduction: JA-SIG Summer Conference 2007 Michael Irion The University of Tulsa
Ruby On Rails: An Introduction: JA-SIG Summer Conference 2007 Michael Irion The University of Tulsa
Michael Irion
The University of Tulsa
What is Ruby on Rails (RoR)?
• Generate application
> rails bookmarks
Directory Layout
• > cd /directorypath/bookmarks
• http://127.0.0.1:3000/hello/sayit
def sayit
render :text => "<h2>Hello World!</h2>"
end
Now for an actual Bookmark
• Edit config/database.yml
development:
adapter: mysql
database: bookmarks_development
username: username
password: password
host: localhost
Create the Database
• URL
• Title
Scaffolding for Bookmarks
located in db/migrate/001_create_bookmarks.rb
def self.down
drop_table :bookmarks
end
end
Running the Migration
>rake db:migrate
def index
@bookmarks = Bookmark.find(:all)
respond_to do |format|
format.html # index.rhtml
format.xml { render :xml => @bookmarks.to_xml }
end
End
Mapping URLs to Controllers and Actions
• http://127.0.0.1:3000/bookmarks/
Located in views/bookmarks/index.rhtml
Add to views/bookmarks/edit.rhtml
<%= text_field_with_auto_complete :bookmark, :url %>
In views/layouts/bookmarks.rhtml, add
<%= javascript_include_tag :defaults %>
Validations
• validates_presence_of
• validates_length_of
• validates_acceptance_of
• validates_confirmation_of
• validates_uniqueness_of
• validates_format_of
• validates_numericality_of
• validates_inclusion_in
• validates_exclusion_of
• validates_associated :relation
Associations - Adding Categories to Bookmarks
• has_one
• belongs_to
• has_many
• has_and_belongs_to_many
• has_many :model1, :through => :model2
Changes to the Database
def self.up
add_column :bookmarks, :category_id, :integer
end
def self.down
remove_column :bookmarks, :category_id
end
>rake db:migrate
Types of Associations
• has_one
• belongs_to
• has_many
• has_and_belongs_to_many
• has_many :model1, :through => :model2
Database Relationships
def edit
@bookmark = Bookmark.find(params[:id])
@categories = Category.find(:all)
end
Associations View Code
<p>
<b>Category</b><br />
<%= collection_select('bookmark', 'category_id',
@categories, 'id', 'name') %>
</p>
Tools
• Textmate (Mac OS X)
• RadRails (Eclipse plugin) www.radrails.org
• Other commercial and opensource IDEs are being
made available
Resources