Monday, 27 April 2015

Rails, Tracks and Routes

I have been learning Ruby for two weeks now, and last week I dived into the Rails framework. As you follow the "Getting Started with Rails" guide, you'll find yourself typing the three magical words in your terminal, rails new blog, upon which if you open your project in any editor you'll see the whole MVC based structure of your new blog project. Pretty neat, huh?

So today I'll be talking about routes. In Rails, when you define any resource in your routes.rb file, Rails will automatically create a bunch of routes for you, some of which would be show, index, update, destroy, etc. But as you move from the very basics towards an actual problem you'll feel the need for some of your own routes.

Now where do you get your custom routes? routes.rb file maybe? If you thought the same thing, then you, my friend, are absolutely right! Here is how you'll define a custom route for your resource.

resources :ironman_suits do
  get 'gallery', on: :collection
end

Did you notice we wrote :collection after we defined our custom route 'gallery'? This will add a route, /ironman_suits/gallery which will apply to the whole collection. You can also define a member route which will apply on a single member whose id will be passed as a parameter.

resources :ironman_suits do
  get 'showcase', on: :member
end

This will recognise /ironman_suits/1/showcase with GET, which you can replace with any of the HTTP verb get, post, put, patch, and delete. Now I see that you're all set for your next fun project with Rails (probably involving a lot of routes), so go ahead and try them out!

No comments:

Post a Comment