Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change routes in ruby on rails?

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.

like image 714
Moon Avatar asked Oct 06 '11 00:10

Moon


People also ask

How do routes work in Ruby on Rails?

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.

How do I see routes in Rails?

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.

What are routes in Ruby?

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.


2 Answers

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.

like image 95
Jordan Running Avatar answered Oct 05 '22 11:10

Jordan Running


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.

like image 27
molf Avatar answered Oct 05 '22 11:10

molf