Article

More RESTful helpers: hash_for_resource_url

When declare a resource in your routes.rb file in Rails, the Simply Restful plugin (now in core) will generate a set of named urls for you. For example, if you do map.resource :users, you’ll get named routes like user_url (#=> users/1) and edit_user_url (#=> users/1;edit). But these named route helpers only give you the string representing the path you’d use to access that particular action. Sometimes you need to merge other parameter into that string.

Well, Rails actually has a helper for that too! When you do map.resource :users, you also get a hash_for_user_url and a hash_for_edit_user_url, which you can then user like this:

link_to user.name, :url => hash_for_edit_user_url(:user_id => user.id, :status => 3)

The keys you supply as arguments to the helper will automatically get merged into the hash. So for the link_to above, you’d get the following URL: /user/1;edit?status=3 .

Comments (No comments)

There are no comments for this post so far.

Post a comment