Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

ruby on rails - How to add a new action to the existing controller?

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...