I just installed Ruby on Rails and created a scaffold called posts
. RoR generated controllers and other required files for me.
I created a new method in posts_controller
, but I can't access it. I looked at other methods that are in the controller and looks like I need to access them by /posts/[MY POST ID]/[MY METHOD NAME]
.
Assuming I created my custom method hello
in the controller, how do i access it?
I looked at routes.rb
, but there's no configuration for it.
Updated:
I understand that I can manually configure it in routes.rb
, but how do all the other methods work? For example, I have "edit
", and "update
" methods in the "posts_controller.rb
" controller. How do those two methods work without configuring routes?
# GET /posts/1/edit
def edit
@post = Post.find(params[:id])
end
I can't find a configuration that matches /posts/[0-9]/edit
pattern.
Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.
TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.
The routing module provides URL rewriting in native Ruby. It's a way to redirect incoming requests to controllers and actions. It replaces the mod_rewrite rules. Best of all, Rails' Routing works with any web server.
The documentation you're looking for is Rails Routing From the Outside In. Once you've read this you'll understand everything Rails does to take your request and point it at method in your controller.
You need to add a route for it to routes.rb
. For example:
# Previous routes
# resources :posts
# Updated routes
resources :posts do
get "hello", :on => :member
end
Have a look at this Rails guide about routing, it should help you understand Rails routing.
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