`
yanzilee9292
  • 浏览: 529782 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Rails3入门锦集(4) Controller的创建,添加,修改,删除代码

阅读更多

入门锦集1-8都来自官方的翻译:http://edgeguides.rubyonrails.org/getting_started.html

 

 

1. 显示一条Post

当你在index页面点击一条文章的链接时,它将指向一条类似 http://localhost:3000/posts/1 的地址。Rails是把它作为show动作资源来解释的,然后传递 1 作为 :id 的参数。下面是 show 动作:

 

def show
  @post = Post.find(params[:id])
  respond_with @post
end

 

 show方法通过传入id值使用 Post.find 来搜索数据库中的单条记录,记录找到之后,Rails使用 show.html.erb 视图进行渲染:

 

<p class="notice"><%= notice %></p>
 
<p>
  <b>Name:</b>
  <%= @post.name %>
</p>
 
<p>
  <b>Title:</b>
  <%= @post.title %>
</p>
 
<p>
  <b>Content:</b>
  <%= @post.content %>
</p>
 
 
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

 

 

2. 编辑Posts

和创建Post一样,编辑post也是一个两部分处理。第一步请求 edit_post_path(@post) , 该方法将调用控制器中的 edit 动作:

 

def edit
  @post = Post.find(params[:id])
end

 

 找到请求的记录之后,Rails使用 edit.html.erb 视图显示出来:

 

<h1>Editing post</h1>
 
<%= render 'form' %>
 
<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>

 

 和 new 动作一样,Rails使用相同的 _form.erb 局部模板,不过这次,该表单将使用 PUT 方式到 PostsController, 而且提交按钮将显示为 “Update Post”。注意这里的 <%= link_to 'Show', @post %> 实际上是 <%= link_to 'Show', @post.id %>。

 

提交由该视图创建的表单将调用 update 动作:

 

def update
  @post = Post.find(params[:id])
  if @post.update_attributes(params[:post])
    respond_with @post, :notice => 'Post was successfully updated.' 
  else
    render :action => 'edit'
  end
end

 在update方法中,首先rails使用:id参数获取数据库中相应的post记录,然后使用 update_attributes 来更新表单中的内容到数据库中。如果更新成功,转到 show 页面,如果更新失败,那么重新回到 edit 页面。

 

 

3. 删除一条Post

最后,点击一条post的删除链接将请求destroy动作。

 

def destroy
  @post = Post.find(params[:id])
  @post.destroy
  respond_with @post
end

destroy方法将从数据库中移除相应的记录,然后浏览器将跳转到 index 页面。

 

 

转自: http://onia.iteye.com/blog/826935

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics