Rails 3 routes with same name, different param name based on constraint

Hello there fellow RoR enthusiasts,

I have been wrestling with rails 3 routes for hours trying to accomplish the following:

I want to use the *same url helper* (photo_url) in my views but have a different route match made depending on the format of the parameter I pass. Seems simple enough, right??

If the parameter looks like nn.nn.nnnnnn.whatever, I want the param passed to "photos#show" to be called :site_photo_id. If the parameter looks like an integer, I want the param passed to be :id.

I have tried the following:

match "/photos/:site_photo_id", :to => "photos#show", :as => "photo", :constraints => {:site_photo_id => /\d{2}\.\d{2}\..*/}

match "/photos/:id", :to => "photos#show", :as => "photo", :constraints => {:id => /\d+/}

If, in my view, I use a string like

"/photo/#{photo.id}"

it works.

But, again, I want to be able to use

photo_url(photo.id)

Can I do that?

TIA, Dan

Hi,

What about to create a default route and just let the manage with the controller?

Is it too wrong?

Kleber Shimabuku wrote in post #1025300:

Hi,

What about to create a default route and just let the manage with the controller?

Is it too wrong?

I want the parameter name to correctly identify the source of the image so the controller knows where to get it.

thx, D

Seems like it would be a lot easier to just have the logic in the controller.

Right now you have the logic in the routes, then you’ll also need logic in the controller to check whether params[:id] or params[:site_photo_id] exists.

If you have just one route and move the logic to the controller, you’ll accomplish what you’re looking for, and avoid repeating logic in routes and controller.

routes.rb

match “/photos/:id”, :to => “photos#show”, :as => “photo”, :constraints => {:id => /.*/}

photos_controller.rb

def show

if params[:id] =~ /\d{2}.\d{2}..*/

# it's a site_photo_id

end

end