简体   繁体   中英

Rails: How to know which route will be 'called'

I'm still trying to get to grips with Rails (Sorry to those people whose answers I haven't yet accepted. I assume you're right, but I haven't yet understood your answers).

I think my problem is I don't know how to tell which route will be 'triggered' when a user clicks a page element.

I understand how routes are mapped to paths, and how the paths (depending on the http verb) point to different controllers and actions.

I don't understand what decides which ROUTE is called.

Specifically, in my project I'm trying to display a set of quiz questions. When a user clicks the submit button, which part of the code determines which route is triggered? (I don't mean the path - I know that's mapped in config/routes.db - I'd like to know which ROUTE is triggered).

I know this might seem like a general question, but not understanding this is directly affecting my ability to progress a Rails project I'm developing.

Can anyone tell me what determines the ROUTE that gets sent into Rails? Is it the object type or resource that the current page is dealing with? I just can't tell. I assume there's something fundamental that I'm not 'getting' but I don't know what that is.

I have been reading the Hartl book and the 'getting started with Rails' guides, but I have not yet come across an explanation that has clarified this for me.

If you look at the <form> element that the form_for helper builds you will see that it has a method and action attribute set by the form_for helper.

The method attribute for creating and editing objects is set to post and the action is set depending on the state of the object passed in to the form_for helper.

When you pass a new instance of an object eg form_for @post do |f| the action attribute will have the value /posts . Rails routes will see this and know to route to the create method in the posts controller.

When an object of an existing post is given to the form_for helper the action attribute will have the value /posts/:id . When a user clicks submit the form will post to that action and rails routes will know that your posting/updating a post that already exists. Rails routing and will route to the update method of the posts controller and put the posts id into the params hash.

Rails uses the type of request ( GET/POST/PUT/DELETE ) and the url to determine which rules in your routes.rb matches that specific combination. It then dispatches the request to the appropriate controller action.

For a detailed understanding on defining your routes, the official guide on routing is a great place to start.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM