如何向现有控制器添加新操作? [英] How to add a new action to the existing controller?

查看:48
本文介绍了如何向现有控制器添加新操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手.对不起,菜鸟问题.

I'm pretty new in Rails. Sorry for the noob question.

我创建了一个新控制器:rails new controller Say hello goodbye

I've create a new controller: rails new controller Say hello goodbye

如何向现有控制器添加hello"和goodbye"等新动作?

How can i add a new action like "hello" and "goodbye" to this existing controller?

推荐答案

添加新动作很简单.您所要做的就是在控制器上添加一个方法,例如:

Add a new action is simple. All you have to do is add a method on your controller, like, for example:

# app/controllers/dummy_controller.rb
def get_back
  logger.warn "It works!"
  redirect_to :back
end

现在,为了能够通过 URL 访问此操作,您需要为此设置一个路由.这是在您的 config/routes.rb 文件中完成的.您可以将其添加为硬路由,例如

Now, to be able to access this action throgh a URL, you need to have a route for that. This is done in your config/routes.rb file. You can add it as a hard route, like

get '/go_back', to: "dummy#get_back"

这是最简单的路线.但您可能希望它表现得像一条宁静的路线.如果您对一个或多个模型执行操作,这将非常有用.所以在你的路由文件中,你会有这样的东西:

This is the simplest possible route. But you might want it to behave like a restful route. This is useful if you are doing an action over one or more models. So in your route file, you will have something like this:

resources :dummy do
  collection do
    get 'get_back'
  end
end

这允许您在集合上接受 get 方法.您将拥有帮助程序 dummy_go_back_url,要访问此页面,网址为 /dummies/go_back.

This allows you to accept a get method over a collection. You will have the helper dummy_go_back_url, and to get to this page the url is /dummies/go_back.

这是用于对资源集合进行操作.如果您正在对一个特定对象进行操作,则应指定一个 member 操作:

This is for acting over a collection of resources. If you are acting on one specific object, you should specify a member action:

resources :dummy do
  member do
    get 'get_back'
  end
end

由于成员操作仅针对一个对象,因此您将拥有一个类似于 /dummies/123/go_back 的 url.这会自动将控制器中的变量 params[:id] 设置为 123,让您轻松获取对象.此外,辅助方法 dummy_go_back_path 被定义,并接收一个对象或 id 作为参数以生成正确的 url.

Since a member action is for only one object, you will have a url like /dummies/123/go_back. This automatically will set the variable params[:id] in your controller to 123, allowing you to easily fetch your object. Also, the helper method dummy_go_back_path is defined, and received one object or id as parameter to generate the correct url.

这些是您可以拥有的最简单的路线,但您可以查看室外路线 来自作为可靠信息来源的 Rails 指南.

These are the most simple routes you can have, but you can look in routing outside in from rails guides as a reliable source of information.

这篇关于如何向现有控制器添加新操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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