stonean

Rails Routes

I don’t frequently have the need to create anything more than the basic “map.resources :model” route. As things go, this means I don’t remember how to anything other than the basic routes and forget the difference between :collection and :member and how that translates to urls and helper methods. So, I’m creating this page as a reference for myself so I don’t have to google and piece together bits of information.

Basic:

map.resources :users

# Which gives you the following helpers:
users_path
users_url
new_user_path
new_user_url
user_path(@user)
user_url(@user)
edit_user_path(@user)
edit_user_url(@user)

# Accessed via:
/users
/users/new
/users/1
/users/1/edit

Nested:

map.resources :posts do |posts|
  posts.resources :comments
end

# Which gives you the following helpers:
post_comments_path
post_comments_url
new_post_comment_path
new_post_comment_url
post_comment_path(@post,@comment)
post_comment_url(@post,@comment)
edit_post_comment_path(@post,@comment)
edit_post_comment_url(@post,@comment)

# Accessed via:
post/1/comments
post/1/comments/new
post/1/comments/1
post/1/comments/1/edit

Adding methods outside the standard REST methods.

map.resources :users, :collection => {:active => :get}

# Which gives you the following helpers:

active_users_path
active_users_url

# Accessed via:

/users/active

The member option means you’re going to access a ‘member’ of the collection. Why this didn’t stick the first time, I have no idea. I’m just slow I guess.

map.resources :users, :member => {:activate => :post}

# Which gives you the following helpers:
activate_user_path(@user)
activate_user_url(@user)

#Accessed via:

/users/1/activate

There will be more added as I run across more usage needs. Let me know if I messed anything up here.

Written by stonean

August 14, 2008 at 10:45 pm

Posted in RubyOnRails

One Response

Subscribe to comments with RSS.

  1. thank you soooo much.

    Anonymous

    October 17, 2008 at 8:00 pm


Comments are closed.