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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With