before anyone get's mad I would like to start by apologizing by how stupid it may seem to some but i'm really having a hard time finding out how.
I have been looking through tutorials online on how to program in ruby on rails but I can't seem to find out how to make a button that does it's action and won't redirect to another page. For example when I want my program to count the number of people present in my database I need to make another view where the action would be executed. I would like to make it do the action on the same view and not redirect to another page. Every tutorial that I've gone through only redirects the action to another page. Could anyone please help me? Thanks in advance.
Suppose that you want to have that button in an index
page of some controller. If you add something like this (I'm using HAML here):
= link_to "Something"
Then clicking the link will refresh the page but calling the index
method of your controller again before rendering. Now the only problem is to figure out if the index
method has been called by clicking on the Something
link or just by calling the page? You can do this by passing some parameters (eg ?mylink=true
) when clicking the link.
HOWEVER I personally prefer to implement a custom controller method (via routes.rb
) and then redirect to the desired page (eg index
). Something like this:
routes.rb
resource :my_resource
collection do
get "test"
end
end
my_resource_controller.rb
...
def test
# Do stuff
redirect_to action: "index
end
my_resource/index.html.haml
= link_to "Something", text_my_resource_path
Now clicking on Something
link gets you to test
method and after doing your stuff you are redirected back to where you were (ie index
). Read more about redirect_to
HERE .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.