上一节里,我们搭建了一个数据库的结构,并用index验证了request-response cycle,如下图:

1. Add show method into Controller

这一节,我们要继续丰富我们的controller:

While index gave all categories, show allows us to access one category. This this is helpful when we want to show just one Category at a time in our Etsy app.

The show method works like this. we write:

  1. def show
  2. @category = Category.find(params[:id])    #it's a hash that we use to find an object by its unique id
  3. end

The show method finds a single category of a given id and stores it in @category. Look a little closer at params[:id]. Seem familiar?

It's a hash that we use to find an object by its unique id. We can find the exact object we want.

我们知道,【在main Controller里的每个action都需要一个route & view】

这里我们在controller里加入了show method,Rails自动update了the route and the view for us.



提醒:在route.rb文件中,我们已有的语句:resources :categories已经takes care of our route for show. Rails 还创建了show.html.erb在我们的Views中!

Rails did this for show, just like it did for the index method.



Rails generates these when we enter methods in your rails generate controller command[rails generate controller Categories index show new edit delete], other we need do it manually.



此时我们的routes.rb还是老样子:

Rails.application.routes.draw do
get '/' => 'pages#home' resources :categories
get 'categories/:id/delete' => 'categories#delete', :as => :categories_delete
end

**show.html.erb:

<%= render 'shared/topnav' %>
<p>
  <strong>Name:</strong>
  <%= @category.name %>
</p> <p>
  <strong>Thumburl:</strong>
  <%= image_tag @category.thumburl %>
</p> <%= link_to 'Edit', edit_category_path(@category) %> |
<%= link_to 'Back', categories_path %> <%= render 'shared/footer' %>

**request in browser: http://localhost:8000/categories/1

we get:



我们再请求一些url如: localhost:8000/categories/2 能得到对应的改变。



这里我就有个疑问,为何routes.rb文件里没有体现出任何对 url 请求的处理的代码,比如,它怎么区分 /categories 和 /categories/1 这俩请求的

2. Forms in html - 表单请求

在我们开始下一个method之前,先看看form - 表单。

Forms are used all over the internet to get input from users. Anytime you fill in information online - signing up for a website or buying shoes, you use a form.

>>Rails gives us a way to create forms called form_for . Let's take a look:

 <%= form_for (@category) do |f| %>  <!--for the person at hand, we'll pass the following information to our form.-->
<div class="field">
<%= f.label :name %><br> <!--Heading for name, labels in Rails, allow us to label our field -!--冒号后面不能有空格--->
<%= f.text_field :name %> <!--The field where we put our stuff, text_field is for text, -->
</div> <div class="field">
<%= f.label :thumburl %><br>
<%= f.url_field :thumburl %> <!--rails we can use url_field for things like urls-->
</div> <div class='actions'>
<%= f.submit %> <!--the button to submit the form.-->
</div>
<% end %>

All this information gets saved in a file called
_form.html.erb[_form.html.erb]!

===================================

好了,我们要接着写 增加 的Controller methods 了。

3. Add 'new' and 'create' method into Controller

增加一个条目的method是成对出现的: new  & create

the 'new' method look like this:

def new
@category = Category.new #creating a whole new instance of Category, and storing it in @category
end

但是建立了一个instance of Category还不够,它并没有保存,需要建立'create' method.

The create method looks like this:

def create
@category = Category.new(category_params) #save that information as our new data through our strong params method
if @category.save
redirect_to(:action => 'index') #If it saves, we redirect to the index page
else
render('new') #otherwise the new page will render again.
end
end

此时的 *** app/controllers/categories_controller.rb 文件就成了:

class CategoriesController < ApplicationController
def index
@categories = Category.all
end def show
@category = Category.find(params[:id])
end def new
@category = Category.new
end def create
@category = Category.new(category_params) # I do not udrstand the .new and the ()
if @category.save
redirect_to(:action => 'index')
else
render('new')
end
end def edit
end def delete
end private
def category_params
params.require(:category).permit(:name, :thumburl)
end end

在浏览器中请求:localhost:8000/categories/new, 我们得到:





>>> 接着我们就来编辑这个 app/views/categories/new.html.erb 文件,我们使用引用 _form.html.erb 的方式,直接一句语句引用过来:

<%= render 'form' %>

so,new.html.erb 文件里:

<%= render 'shared/topnav' %>

<h1>New Category</h1>

<!-- Render form here -->
<%= render 'form' %> <%= link_to 'Back', categories_path %> <%= render 'shared/footer' %>

然后我们就得到了这个:

===================================

好了,我们要接着写 改 的Controller methods 了。

4. Add 'edit' and 'update' method into Controller

修改一个条目的method是成对出现的: edit  & update

Edit and Update methods are also related. The edit method will give us the ability to edit information and the update method will save the information we edit!

The edit method looks like this:

def edit
@category = Category.find(params[:id])
end

edit method 就是根据id找到category并把它存入@category中。跟show method是一模一样的。这还不够,我们还要一个update method来存它。

def update
@category = Category.find(params[:id]) #find a category by its id
if @category.update_attributes(category_params)
redirect_to(:action => 'show', :id => @category.id)
else
render('index')
end
end

所以此时我们的**app/controllers/categories_controller.rb文件就成了:

class CategoriesController < ApplicationController
def index
@categories = Category.all
end def show
@category = Category.find(params[:id])
end def new
@category = Category.new
end def create
@category = Category.new(category_params)
if @category.save
redirect_to(:action => 'index')
else
render('new')
end
end def edit
@category = Category.find(params[:id]) #finds a single category of a given id and stores it in @category
end def update
@category = Category.find(params[:id]) #finds a person by its id and stores it in person
if @category.update_attributes(category_params)#check if the attributes are updated in our model
redirect_to(:action => 'show', :id => @category.id)#go to show page for that object
else
render('index') #render our index again
end
end def delete
end private
def category_params
params.require(:category).permit(:name, :thumburl)
end end

In your browser, visit localhost:8000/categories/1/edit to see what you created.

接下来是修改view: app/views/categories/edit.html.erb

We just need an edit page and the update page will process the information.

Here, our form_for comes in handy again. We go to our edit page and write:
<%= render 'form' %>


That's it. We're good!

<%= render 'shared/topnav' %>

<h1>Edit Category</h1>

<!-- Render form here -->
<%= render 'form' %> <%= link_to 'Back', categories_path %> <%= render 'shared/footer' %>

浏览器请求:http://localhost:8000/categories/1/edit

===================================

好了,我们要接着写 删 的Controller methods 了。

5. Add 'delete' and 'destroy' method into Controller

delete and destroy method.The delete and destroy methods go together. The delete method will give us the ability delete information, and the destroy method will permanently destroy it! The 'delete' method 是我们可以拿来删除信息的,the 'destroy' method是让我们永久去除它的。

we could write a delete method like this:

def delete
@category = Category.find(params[:id])
end

它看起来有点像show & edit,The destroy method looks like this:

def destroy
Category.find(params[:id]).destroy
redirect_to(:action => 'index')
end

Here we find a category we want to permanently delete. Once we delete it, we get redirected to the index page.

修改view: app/views/categories/delete.html.erb 成:

<p>
<strong>Name:</strong>
<%= @category.name %>
</p> <p>
<strong>Thumburl:</strong>
<%= image_tag @category.thumburl %>
</p> <%= link_to "Delete", categories_delete_path(:id => @category.id) %> |
<%= link_to 'Edit', edit_category_path(@category) %> |
<%= link_to 'Back', categories_path %> <p>1</p>
<p>2</p>
<p>3</p>

然后浏览器中请求:localhost:8000/categories/1/delete, 得到:

Congratulations! You created the Categories page of the Etsy app. We did this by creating the Model, Controller, and Views for Categories.

总结一下:

We first generated the Category Model using a terminal command. We added columns to our Categories Migration table and migrated and seeded our database.

We then generated a Categories Controller with the index, show, new, edit, and delete methods. This gave us a route and View for those methods.

We created Controller methods for eight of our CRUD actions, and Views for index, show, new, edit, and delete.

  • 首先在terminal command里建立了Model, 我们在注入表里加入了columns到Categories,并且,我们Seeded our database.
  • 然后我们建立了categories controller with the index, show, new, edit, and delete methods. 这让我们有了routes 和 view for those methods.
  • 我们8个CRUD actions 所需的methods都建立在了controller里,index, show, edit ,and delete所需的Views也建立了。

Ruby学习笔记5: 动态web app的建立 (2)的更多相关文章

  1. Ruby学习笔记4: 动态web app的建立

    Ruby学习笔记4: 动态web app的建立 We will first build the Categories page. This page contains topics like Art, ...

  2. Ruby学习笔记6: 动态web app的建立(3)--多Model之间的交互

    We first built a static site which displayed a static image using only a Controller and a View. This ...

  3. JavaWeb学习笔记——开发动态WEB资源(一)Java程序向浏览器输出数据

    开发一个动态web资源,即开发一个Java程序向浏览器输出数据,需要完成以下2个步骤: 1.编写一个Java类,实现Servlet接口 开发一个动态web资源必须实现javax.servlet.Ser ...

  4. JavaWeb学习笔记——开发动态WEB资源(八)cookies和httpsession

    会话: cookies: (1)cookies是WEB服务器发送到浏览器的简短文本信息 (2)cookies可以禁用 httpsession: 一次会话是从你打开浏览器开始到你关闭浏览器结束 提供一种 ...

  5. JavaWeb学习笔记——开发动态WEB资源(六)ServletConfig和ServletContext

    1.只有在第一次请求服务器产生实例的时候才会调用init()方法,有一种办法能在服务器一启动的时候就加载init()方法. 即服务器启动即加载Servlet,且按数字大小顺序实例化Servlet. 方 ...

  6. JavaWeb学习笔记——开发动态WEB资源(五)servlet身份验证

    本工程的功能是实现Javaweb的servlet身份验证 一下是login.html文件中的代码 <!DOCTYPE html> <html> <head> < ...

  7. JavaWeb学习笔记——开发动态WEB资源(四)打印当前使用的是get方法

    该工程的名称是testhttp,功能是在页面中表格打印浏览过程中的相关头信息. 新建一个工程,然后在这个工程里面新建一个servlet,这样便可以省去编写web.xml的过程 以下是TestHttpS ...

  8. JavaWeb学习笔记——开发动态WEB资源(三)显示当前时间

    该工程的功能是实现在页面中显示当前的时间 以下的代码是HelloServlet.java中的代码 package helloapp2; import java.io.IOException; impo ...

  9. JavaWeb学习笔记——开发动态WEB资源(二)HelloWord

    该工程的功能是在页面上输出一段话 首先在src里面新建一个class,在interface里面添加javax.servlet.Servlet 以下是HelloServlet.java中的代码: pac ...

随机推荐

  1. 转:区块链开发(一)搭建基于以太坊go-ethereum的私有链环境

    区块链开发(一)搭建基于以太坊go-ethereum的私有链环境 wo541075754 · 2016-11-07 13:00:03 · 3730 次点击 · 预计阅读时间 3 分钟 · 约1小时前  ...

  2. 2017.11.7 ant design - upload 组件的使用, react 条件渲染以及 axios.all() 的使用

    一.主要任务:悉尼小程序管理后台,添加景点页面的开发 二.所遇问题及解决 1. 上传多个不同分类音频信息时,如中文音频和英文音频,要求音频不是放在一个数组中的,每个音频是一个独立的字段,此时: < ...

  3. MySQL的瑞士军刀

    这里主要讲mysql运维中的一些主要工具,这些工具可能大家都用过,特别是系统管理员或者做linux服务器维护的同学可能都知道这些小工具,这里讲得会比较多一些,除了系统监控的小工具,还包括一些mysql ...

  4. jQuery模态框实现 后台添加删除修改Ip端口

    主要用到,$('#i1').each(),标签里绑定函数可传参数this <!DOCTYPE html> <html lang="en"> <head ...

  5. sublime text2+Ctags+Cscope替代Source Insight

    说明:以Windows系统下查看C++代码为例.因为Source Insight(以下简称SI)是收费软件,且界面丑陋,所以考虑其替代方案,发现Sublime Text3(以下简称ST3) + Cta ...

  6. Android 项目中的资源获取方法

    Android资源文件分类: Android资源文件大致可以分为两种: 第一种是res目录下存放的可编译的资源文件: 这种资源文件系统会在R.java里面自动生成该资源文件的ID,所以访问这种资源文件 ...

  7. NGUI的字体加粗效果

    ngui的UILabel可以通过属性面板(inspector)设置字体的样式:加粗 倾斜 正常等. 但是如果通过这里设置了加粗,与实际的加粗不一样,ngui有一个拉伸宽度的变化. 这让人觉得很丑 .如 ...

  8. code block自动生成makefile

    安装插件 http://developer.berlios.de/projects/cbmakegen/  然后会在project菜单下面有一个Generate Makefile的选项 点击就行了 如 ...

  9. 廖雪峰Java3异常处理-2断言和日志-1使用断言

    1.断言 断言Assertion是一种程序调试方式 使用assert关键字 断言条件预期为true 如果断言失败,抛出AssertionError,停止程序 可选的断言消息,断言失败,就会抛出 pub ...

  10. 敏捷软件开发——第8章 SRP:单一职责原则

    第8章 SRP:单一职责原则 一个类应该只有一个发生变化的原因. 8.1 定义职责 在SRP中我们把职责定义为变化的原因.如果你想到多于一个的动机去改变一个类,那么这个类就具有多于一个的职责.同时,我 ...