`
yanzilee9292
  • 浏览: 545533 次
  • 性别: 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

分享到:
评论

相关推荐

    Ruby on Rails Guides v2 - Ruby on Rails 4.2.5

    ### Ruby on Rails Guides v2 - Ruby on Rails 4.2.5 #### 一、重要概念及基础假设 - **重要概念**:本指南旨在帮助读者深入理解Ruby on Rails(以下简称Rails)4.2.5版本的核心功能与最佳实践。 - **基础假设**:...

    rails敏捷开发,我的成功之路

    - **数据迁移**:介绍了如何使用Rails的迁移功能来管理数据库结构的变化,包括创建表、修改字段等操作。 - **ActiveRecord高级用法**:除了基本的CRUD操作外,还包括关联关系的处理、事务管理等高级特性。 ### 知识...

    Ruby on Rails 指南 v5.0.1 中文版

    #### Rails入门 - **前提条件**:为了能够顺利地开始Rails的学习之旅,读者需要具备一定的Ruby语言基础,并且对Web开发有一定的了解。 - **Rails是什么?**:Rails是一种用于开发服务器端应用程序的模型-视图-控制...

    Ruby On Rails

    迁移(Migrations)则用于管理数据库结构的变化,允许你在应用的生命周期中方便地添加、修改或删除表。 TDD(测试驱动开发)在RoR中受到推崇,它提倡先写测试,再编写满足测试的代码。RoR内置了Test::Unit和RSpec等...

    简单入门新闻发布系统

    3. **MVC(Model-View-Controller)模式**:一种软件设计模式,用于组织代码结构,使系统更易于维护和扩展。 4. **CRUD操作**:Create(创建)、Read(读取)、Update(更新)、Delete(删除),是新闻发布系统中...

Global site tag (gtag.js) - Google Analytics