Rails:路线,控制器,视图,噢,我的感叹号 [英] Rails: Routes, Controllers, Views, Oh My(exclamation)

查看:67
本文介绍了Rails:路线,控制器,视图,噢,我的感叹号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解路线,控制器和视图之间的关联(以及它们之间的连接方式).

I'm failing to understand the correlation between routes, controllers, and views (and how they connect to each other).

因此,我的控制器具有indexshownewcreatedestroy方法.以及相应的

So, I've got my controller with the index,show,new,create,destroy methods. And the corresponding

GET    /entries(.:format)                     entries#index
POST   /entries(.:format)                     entries#create
GET    /entries/new(.:format)                 entries#new
GET    /entries/:id/edit(.:format)            entries#edit
GET    /entries/:id(.:format)                 entries#show
PUT    /entries/:id(.:format)                 entries#update
DELETE /entries/:id(.:format)                 entries#destroy

例如,如果我添加一个新方法vote_upvote_down,并且视图具有匹配的动作名称,那怎么办呢?

How come if I add a new method vote_up or vote_down, for example, and the views with matching action names, it doesn't work.

1)添加新操作并将它们连接到视图的正确方法是什么? 2) Bonus 使这些方法与ajax兼容(用ajax呈现部分)的正确方法是什么?如果用户未启用js,会发生什么情况?

1) What is the proper way to add new actions and connect them to views? 2) Bonus What is the proper way to make these methods ajax-compatible (render a partial with ajax)? What happens if the user doesn't have js enabled?

我可以根据我得到的答案来扩展/发展这个问题.

我已经厌倦了使用诸如自定义操作路线栏杆之类的工具来搜索我的应用程序.这是排水和糟糕的形式,我终于可以理解这种术语了-我已经100%自学了...所以请尝试了解是否可以为一个年轻的巴达旺人.

I'm tired of googling things like custom action route rails and the like to hodge-podge my apps. It's draining and poor form and I'm finally getting to the level to comprehend the lingo--I've been self taught 100%...so please try to be understanding if you can for a young padawan.

推荐答案

从一开始就是这里的思考方式:

Here's how to think of it, from the beginning:

1)您的应用唯一要做的一件事就是响应HTTP请求.

最典型的请求是:

  • GET-用户在浏览器的URL栏中键入一些内容,然后按Enter.

  • GET - the user types something into the URL bar of their browser and hits enter.

POST-用户提交表单.

POST - the user submits a form.

还有其他类型的HTTP请求,最重要的是PUT,PATCH和DELETE. Rails遵循REST模式,这意味着它为这些HTTP动词分配了特定的含义.

There are also other kinds of HTTP requests, most importantly PUT, PATCH and DELETE. Rails follows the REST pattern, which means it assigns specific meanings to these HTTP verbs.

2)当任何请求进入您的应用程序时,必须将其路由到Controller Action.

您的routes.rb文件是Rails路由器(ActionDispatch)的一组指令,该指令告诉路由器将请求发送到哪里. 标准" rails资源是作为快捷方式给出的,如下所示:

Your routes.rb file is a set of instructions for the Rails Router (ActionDispatch) that tells the router where to send requests. The "standard" rails resource is given as a shortcut, like this:

resources :things

这意味着:

GET /things => things#index

GET /things/:id => things#show

GET /things/new => things#new

GET /things/edit/:id => things#edit

POST /things => things#create

PUT /things/:id => things#update

DELETE /things/:id => things#destroy

这些被认为是标准的RESTful操作-您的resources :things声明没有其他设置.因此,如果您希望控制器执行其他非标准动作,则必须手动添加它们.

These are considered the standard RESTful actions - nothing else is set by your resources :things declaration. So, if you want the controller to perform other non-standard actions, you have to add them manually.

如果要对特定记录执行操作,最好的方法是使用:

If you want to perform an action on a specific record, the best way is to use:

resources :things do
  member do
    get 'vote_up'
  end
end

这告诉路由器,如果有人向/things/123/vote_up发出GET请求,则它应该触发ThingsController vote_up动作.

This tells the router that if someone makes a GET request to /things/123/vote_up that it should trigger the ThingsController vote_up action.

铁路指南,您应该阅读全文.

3)控制器的工作是发送对请求的响应.

通常,这意味着要从数据库加载记录并呈现该记录的视图.

Normally this means something like loading a record from the database and rendering the view for that record.

每个控制器操作都通过将响应发送回传入请求而结束.此响应可以是render调用-意味着以某种格式发送一些数据,也可以是redirect调用-基本上为您提出了新请求,因此您可以得到该其他请求的响应.

Each controller action ends by sending the response back to the incoming request. This response can be either a render call - which means send back some data in some format - or a redirect call - which basically makes a new request for you and therefore you get the response of that other request.

在Rails中,重定向有效地将请求发送到其他控制器操作.

In Rails a redirect is effectively sending the request to a different controller action.

Render调用发送数据作为对请求的响应.

A Render call sends data as a response to the request.

当您调用render :new时,这是render :template => :new的快捷方式,它将加载app/views/things/new.html.erb(或任何其他形式)模板,从控制器(通常是您的实例变量)发送数据,并使用该模板对其进行求值语言(erb,halm等),这会产生很大的HTML字符串,然后控制器会将其传递给浏览器.

When you call render :new, this is a shortcut to render :template => :new, which loads the app/views/things/new.html.erb (or whatever) template, sends it the data from the controller (normally your instance variables) and evaluates this using the template language (erb, haml, etc.) This results in a big string of HTML, which the controller then delivers to the browser.

想自己看看这是什么吗?尝试以render :text => 'Hello World'甚至甚至以

Want to see what this for yourself? Try ending a controller with render :text => 'Hello World', or even:

render :inline => '<!DOCTYPE html><head><title>Inline Wow!</title></head><body>Mind blown.</body></html>'

看看会发生什么.

在响应(渲染)时,您可以发送普通" HTML模板,其中包含整页的信息(头部,正文等),或Ajax使用的部分信息.您还可以发送原始数据,例如JSON或XML.实际上,它们全都是文本,并且根据文本的内容(以及随之而来的HTTP标头),浏览器,脚本或客户端应用程序会相应地对其进行处理.

When responding (rendering) you can send "normal" HTML templates, with a whole page worth of information in it (head, body, etc.), or a partial that is used by Ajax. You can also send raw data such as JSON or XML. It's all actually just text, and depending on the content of that text (and the HTTP headers that come with it) the browser, script, or client application handles it accordingly.

同样,请参见铁路指南.

4)当浏览器发出请求时,您可能希望发送回HTML.如果该请求是由Ajax发出的,则您可能希望发送回JSON.

对于像vote_up这样的自定义操作,您可能根本不想显示模板,而只是重定向.因此,您可能会遇到类似这样的情况:

In the case of a custom action like vote_up you might not want to show a template at all, but just redirect. So, you might have something like this:

ThingsController < ApplicationController

  def vote_up
    @thing = Thing.find(params[:id])
    @thing.vote_up
    redirect_to @thing
  end

end

现在,路由器的优点之一是它将为您提供URL帮助程序.如果您已经如前所示创建了路线和动作,则在显示内容"页面上可以有一个如下网址:

Now, one of the benefits of the router is it will give you URL helpers. If you've created the route and action as shown before, on your "show thing" page you could have a URL like this:

link_to 'Vote up this thing!', vote_up_thing_path(@thing)

这将创建一个指向things/123/vote_up的链接,如果有人单击它,它将在ThingsController上的vote_up动作中运行代码,然后重定向回显示视图.

That would create a link to things/123/vote_up, and if someone clicked on it it would run the code in the vote_up action on the ThingsController, and then redirect back to the show thing view.

5)您的模板使用链接和表单将消息发送到控制器.链接发出GET请求,表单发出POST请求.

如果您想开始收到AJAX请求,那很好.在这种情况下,您只需要使用Javascript发出请求并处理响应即可.因此,例如,您可以在模板中放入以下内容:

If you want to start having AJAX requests, that's fine. In that case, you just need to make the request in Javascript, and handle the response. So, for instance, you could put something like this in your template:

= link_to 'Vote up this thing', vote_up_thing_path(@thing), :id => 'vote-up-button'

然后在Javascript(使用jQuery)中,您可以具有以下功能:

Then in Javascript (with jQuery) you could have a function like this:

$(function(){
  $('a#vote-up-button').click( function(event){
    event.preventDefault();
    $.ajax({
      url: this.attr('href'),
      type: 'GET',
      success: function(){...},
      error: function(){...}
    });
  });
});

在这种情况下,jQuery Ajax方法只是发出一个get请求,然后根据收到的响应运行一个回调函数.

In this case the jQuery Ajax method is just making a get request, and then running a callback function based on the response it got.

6)控制器/路由的结构不会影响您可以发出的请求类型,只会影响对URL上的哪种HTTP方法做出响应的动作.

您在控制器操作中要做的事情确定您是否准备好响应javascript或html请求等.

What you do INSIDE your controller action determines whether you are ready to respond to javascript or html requests etc.

虽然Rails肯定能够使用respond_to块在单个控制器动作中处理多种请求格式,但从实用性的角度来看,当您选择让路由仅响应一种格式或另一个.

While rails is certainly able to handle multiple request formats in a single controller action, using the respond_to block, as a matter of practicality I find things work much more smoothly when you choose to have routes only respond to one format or another.

IE:我将使您的常规页面加载请求(索引,显示,新建,编辑)只是HTML请求,然后我将使您要添加的任何其他AJAX操作仅是Javascript-即.他们使用JSON而不是HTML进行响应.当然,您不必这样做,但是如果这样做,您的生活将会更加轻松.

IE: I would make your normal page load requests (index, show, new, edit) just HTML requests, and then I would make any additional AJAX actions you want to add be Javascript only -- ie. they respond with JSON instead of HTML. You don't have to do this, of course, but your life will be easier if you do.

我希望这可以使您更清楚地了解应用程序中正在发生的事情.欢迎使用Rails,您正在加入一个很棒的社区!

I hope this gives you a clearer sense of what is happening in your app. Welcome to Rails, you're joining a great community!

这篇关于Rails:路线,控制器,视图,噢,我的感叹号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆