现在的位置: 首页 > 综合 > 正文

Rails3教程系列之四:Rails3入门(4)

2018年04月19日 ⁄ 综合 ⁄ 共 2141字 ⁄ 字号 评论关闭

Rails3教程系列之四:Rails3入门(4)

文章出处:http://edgeguides.rubyonrails.org/getting_started.html

1. 显示一条Post

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

Ruby代码 复制代码
收藏代码
  1. def show 
  2.   @post = Post.find(params[:id]) 
  3.   respond_with @post 
  4. end 

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

Html代码 复制代码
收藏代码
  1. <p
    class="notice"><%= notice %></p> 
  2.   
  3. <p> 
  4.   <b>Name:</b> 
  5.   <%= @post.name %> 
  6. </p> 
  7.   
  8. <p> 
  9.   <b>Title:</b> 
  10.   <%= @post.title %> 
  11. </p> 
  12.   
  13. <p> 
  14.   <b>Content:</b> 
  15.   <%= @post.content %> 
  16. </p> 
  17.   
  18.   
  19. <%= link_to 'Edit', edit_post_path(@post) %>
  20. <%= link_to 'Back', posts_path %> 

2. 编辑Posts

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

Ruby代码 复制代码
收藏代码
  1. def edit 
  2.   @post = Post.find(params[:id]) 
  3. end 

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

Html代码 复制代码
收藏代码
  1. <h1>Editing post</h1> 
  2.   
  3. <%= render 'form' %> 
  4.   
  5. <%= link_to 'Show', @post %>
  6. <%= link_to 'Back', posts_path %> 

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

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

Ruby代码 复制代码
收藏代码
  1. def update 
  2.   @post = Post.find(params[:id]) 
  3.   if @post.update_attributes(params[:post]) 
  4.     respond_with @post, :notice =>
    'Post was successfully updated.'  
  5.   else 
  6.     render :action => 'edit' 
  7.   end 
  8. end 

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

3. 删除一条Post

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

Ruby代码 复制代码
收藏代码
  1. def destroy 
  2.   @post = Post.find(params[:id]) 
  3.   @post.destroy 
  4.   respond_with @post 
  5. end 

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

抱歉!评论已关闭.