5. Running
a Migration
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :name
t.string :title
t.text :content
t.timestamps
end
end
end db/migrate/20100207214725_create_posts.rb
ROR Lab.
7. Adding a Link
<h1>Hello, Rails!</h1>
<%= link_to "My Blog", posts_path %>
app/views/home/index.html.erb
Hello, Rails!
My Blog
ROR Lab.
8. The Model
class Post < ActiveRecord::Base
attr_accessible :content, :name, :title
end
app/models/post.rb
Rails Active
Model Record
database.yml
ROR Lab.
10. Using the Console
$ rails console --sandbox
$ rails c --sandbox
Loading development environment in sandbox (Rails
3.2.6)
Any modifications you make will be rolled back on exit
1.9.3p194 :001 > Post.all
Post Load (0.1ms) SELECT "posts".* FROM "posts"
=> []
1.9.3p194 :002 > reload!
Reloading...
=> true
ROR Lab.
11. Listing All Posts
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @posts }
end
end
app/controllers/posts_controller.rb
1.9.3p194 :004 > posts = Post.all
Post Load (0.2ms) SELECT "posts".* FROM "posts"
=> []
1.9.3p194 :005 > posts.class
=> Array
1.9.3p194 :006 > post = Post.scoped
Post Load (0.2ms) SELECT "posts".* FROM "posts"
=> []
1.9.3p194 :007 > post.class
=> ActiveRecord::Relation
ROR Lab.
12. <h1>Listing posts</h1> Rails makes all of the
<table> instance variables from the
<tr> action available to the view.
<th>Name</th>
<th>Title</th>
<th>Content</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.name %></td>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
:method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New post', new_post_path %>
app/views/posts/index.html.erb
ROR Lab.
18. def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to(@post,
:notice => 'Post was successfully created.') }
format.json { render :json => @post,
:status => :created, :location => @post }
else
format.html { render :action => "new" }
format.json { render :json => @post.errors,
:status => :unprocessable_entity }
end
end
end
ROR Lab.
19. Show a Post
http://localhost:3000/posts/1
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @post }
end
end
ROR Lab.