Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

This will give you a good head start on the routes: http://guides.rubyonrails.org/routing.html

Not every method you make will have its own path, rails is built on the rest principle, and your scaffold created methods in the post controller that follow those paths, like index, show etc....

You can force your method to have a route added to it, but in reality you rarely actually need to do so as following the convention is far easier.

In Rails 3.x

match 'posts/hello' => 'posts#hello'

Available at example.com/posts/hello

When you used scaffold to generate post, it added a line resources :posts in your routes.rb file. That line configures routes for all the controller actions that were generated. As Caleb mentions above, not every action has a dedicated path. A single path can correspond to multiple actions because rails also takes into account the HTTP method. So, for instance, the path /posts with the HTTP method GET corresponds to the controller action index, while the same path with the HTTP method PUT corresponds to the controller action update. You can see these associations when you run rake routes from the console. I agree with Jordan and Caleb that the Rails Guides is a good read and will help you understand routes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top