সোমবার, ২৮ ডিসেম্বর, ২০০৯

rails passing parameters in routes generated path

In Rails for a complete, controlled and structured routing we should specify all paths in routes.
sometimes we may need to send some parameters in route

for example we need a route for saved listing for a user.

we can achieve this by the following in routes.rb
map.resources :users, :collection =>{:saved_listing => :get, :other_action =>:post}

the path might be generated by:

Option 1:
saved_listing_users_path(user)//user is an object

Option 2://passing only id
saved_listing_users_path(:id=>user_id)


If we need to add others parameters in url then,

Option 3://passing id with other params
saved_listing_users_path(:id=>user_id, :lan=>'en', :foo =>'bar')


Option 4://passing only hash
param_hash = {:id=>user_id, :lan=>'en', :foo =>'bar'}
saved_listing_users_path(param_hash)

Sometime we may need to pass all parameters to url, then the following will not works:

saved_listing_users_path(params)
because though params is a hash but it includes :controller, :action in key list.

so we need the followings:

param_hash = params.clone //take params clone not params to avoid reference problem
param_hash.delete_if {|key, value| ['controller', 'action'].include?(key) }
//remove controler and action from params
saved_listing_users_path(param_hash)


we can use mix type in parameters like some key,value pair and a hash.
then we have to use :params key for the hash in parameter list
saved_listing_users_path(:id=>34, :params=>param_hash)


I think this will be helpfull a little.
and you all are welcome to share your thoughts

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন