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

27 views
Skip to first unread message

Dan Sadaka

unread,
Oct 5, 2011, 6:24:06 PM10/5/11
to rubyonra...@googlegroups.com
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

--
Posted via http://www.ruby-forum.com/.

Kleber Shimabuku

unread,
Oct 6, 2011, 3:56:11 AM10/6/11
to Ruby on Rails: Talk
Hi,

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

Is it too wrong?

Dan Sadaka

unread,
Oct 6, 2011, 9:36:11 AM10/6/11
to rubyonra...@googlegroups.com
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

Tim Shaffer

unread,
Oct 6, 2011, 12:41:18 PM10/6/11
to rubyonra...@googlegroups.com
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
Reply all
Reply to author
Forward
0 new messages