Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEthan Rivas
9,979 PointsRun controller method in a rails view on click
Hi!, I've a little question here:
I have a method in my controller called "button" (just for practice):
def button
puts "hi there"
end
The thing is that I want to run this method only when I click a button in my html.erb view, how can I dod this?
Thanks.
1 Answer
Maciej Czuchnowski
36,441 PointsOK, so first you need a route that will point to this action in your routes.rb
. Something like:
get '/button', to: 'your_controller_name#button`, as: 'button`
(I use a get verb here, but in case of buttons you will most likely use a POST or PUT verb)
You will also need some empty view file named button.html.erb
in the proper controllers subforlder - this is where the page will redirect you after the click..
Last step would be adding a button to your original view file. Something similar to this:
<%= button_to 'Press me', button_path, method: :get %>
It's good for practice - knowing what parts are needed to fire up an action in the controller.
Ethan Rivas
9,979 PointsEthan Rivas
9,979 PointsThanks for the clear and detailed explanation, I was very lost in this one, thanks again!