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 trialJeff Lange
8,788 PointsHow does Rails know to call the create method when we click the "Reset Password" button?
I'm not understanding how buttons in Rails apps work. A link makes sense: in the view files we specify exactly what the link does, e.g.
<%= link_to "Edit", edit_todo_list_path(todo_list)%>
However, for buttons, the view just looks like this:
<%= submit_tag "Reset Password" %>
And somehow Rails knows that when we click the button it's supposed to call the create method in the password_resets_controller.rb file. How does it know to do that? Where did we define that behavior? How does it know to call the create method instead of another method? This is probably really simple and I'm just overlooking it.
1 Answer
Maciej Czuchnowski
36,441 PointsNotice that submit buttons in all forms (creating new user, creating new status or list) always call create method by default.
Jeff Lange
8,788 PointsJeff Lange
8,788 PointsOhhhhhh, awesome. Thank you! And now that I think about it, you would never have more than one submit button on a page right? So you wouldn't have to worry about multiple methods for multiple buttons, correct?
Maciej Czuchnowski
36,441 PointsMaciej Czuchnowski
36,441 PointsYeah, I guess so :). Even if you did have more, I think they are always in the context of some form, so they should know which resource's create should be fired.
J Scott Erickson
11,883 PointsJ Scott Erickson
11,883 PointsTo be clear, forms have associated 'resources', and a form must have a resource or path to send its fields to. password_path( resource ). The reason that the form knows what function to call is a function of the config/routes.rb file, which defines all of the available paths for a resource.
So in the most basic terms. Rails ActionPack handles the request coming from the form and determines, based on the config/routes.rb file which controller and which action to call based on the path.