Ruby on Rails,在Controller中指定渲染的Templates

http://blog.csdn.net/abbuggy/article/details/7555423


《Ruby on Rails,Routes配置routes.rb及请求解析规则》中我们了解了如何配置Routes来确定那个Controller和Action被调用,之后的工作就完全由Controller接管了。

很自然Controller的工作就是“控制”,在这里经常会出现很多if,else之类的判断语句。比如说“如果能够从数据库中取得某某,那么去做这个,如果没有能够取得某某,那么去做那个”。或者“如果用户已经成功登陆,那么转向某个页面,如果没有登陆,那么转向登陆页面”等等。
归结起来,Controller的工作主要有两个方面:其一是与Model交互以获取用于显示的信息。其二是转向适当的页面并触发其绘制。

那么Controller是如何确定转向和绘制哪个页面的呢?在《Ruby on Rails,创建最简单的视图/控制器单元Hello World》中我们创建了位于名为demo的Controller位于app/controllers/demo_controller. rb以及名为index的Templates位于app/views/demo/index.html.erb。

class DemoController < ApplicationController
  def index
  end
end

在接收到http://localhost:3000/demo/index的请求时,demo(Controller)中的index方法会被调用,然后自动转向index(Templates),这是Rails中内建的机制。

为了演示Controller的工作原理,再建立一个新的名为hello的Templets位于app/views/demo/hello.html.erb。

<h1>Demo#hello</h1>
<p>Hello Page!</p>

请注意,在demo(Controller)中并没有一个名叫hello的方法,看看在浏览器中输入http://localhost:3000/demo/hello会怎么样,Rails会尝试调用demo(Controller)中的hello方法,如果没有这个方法也无妨,跳过这个环节直接显示hello(Templates)。


如果请求一个并不存在的Templates会怎么样,浏览器中输入http://localhost:3000/demo/something。demo(Controller)中没有名叫something的方法,跳过去显示something(Templates)。但是我们没有这个Templates,页面提示错误了。


那么,在demo(Controller)中到底做了什么呢?实际上

class DemoController < ApplicationController
  def index
  end
end

class DemoController < ApplicationController
  def index
    render('demo/index');
  end
end

的意义是一样的,还有别的写法如

class DemoController < ApplicationController
  def index
    render('demo/index');
  end
end

或者,由于当前就在demo(Controller)中即可省去前面的目录名写成

class DemoController < ApplicationController
  def index
    render('index');
  end
end

当然了前面那种什么都不写的方式最为简便。:)


http://blog.csdn.net/abbuggy/article/details/7555423

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值