开发者

Custom Nested Routing in Rails 2.3

I'm trying to change some URLs in this project I'm working on, but I can't find any examples of what I'm looking for in any documentation and all my attempts seem to end up not working.

Here's what I'm trying to do. I have a post that has several images, and an individual image would be accessed with an URL like this:

/posts/aliased_title/images/2

However, I want to change it so I can remove the "posts" and "im开发者_Python百科ages" part of the URL, change it to something like /aliased_title/2.

I know how to do this for a single controller, but how can I accomplish this with the images controller as well? Can I do this in a way that will generate the "paths" (like post_image_path), or do I need to hard code every single action into the routing?

Thank you in advance.


Depending what your routes and aliased titles look like, you can use something like the following:

resources :images, :path => '/:title/:id', :constrain => { :title => /[a-z_-]+/ }

# in your view
image_path(image.title, image)

Keep in mind that routes match in the order they are defined, so you will want to put this line down at the bottom of your routes file so that it doesn't interfere with routes like /users/2.

All this said, you should strongly consider whether your use case can live with an anchor like /image. It'll prevent a lot of confusing problems with routing that will very likely bite you in the ass down the line. It's not infeasible to do without the anchor, but it does create additional work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜