Ask A Question

Notifications

You’re not receiving notifications from this thread.

Friendly URL's question

Nelson Casanova asked in Gems / Libraries

Hello,

I'm building a small forum for my website and its a very simple app with the schema looking a bit like:

Topic -> Forum -> Post

So, Topic can be 'Off-Topic' with a Forum called 'Introductions' and maybe a post titled 'Hi There'

In an ideal world the index is a list of Topics and each one displaying a link to its underlying Forums. Once you click a forum URL will look like: mysite.com/off-topic/ and once I click a post the URL looks like mysite.com/off-topic/hi-there

Currently what I've got looks more like mysite.com/forums/1/posts/1 feels like if I implement the friendly_id gem I will still end up with something like mysite.com/forums/off-topic/posts/hi-there. How can I achieve a url that does not include the model in it?

Reply

Right, got it. I just hope this is not going to cause major headaches in the future.

I installed friendly_id and add the gem functionality to the topic, forum and post models.

As expected I ended up with a url that looked like mysite.com/forums/off-topic/posts/hi-there not bad but still not optimal.

I added the following to my routes.rb:

resources :forums, :path => '' do
   resources :posts, :path => '' do
     end
end

Done. Like i said, I hope this is the right way...

Reply

Hey Nelson,

The name of the model helps make routing way easier, so that's why it's done that way. Here's an example of why.

You might have a /sign_up route, but if you weren't careful, "sign_up" can easily get treated as a topic, which you don't want.

To do this, you'll just write your own custom routes.

get "/sign_up"

get "/:topic/:forum/:post"
get "/:topic/:forum"
get "/:topic"

This way, sign up should get interpreted first, instead of it being treated as a topic. And the rest of the routes are catch-alls to treat everything else as if it were a topic and so on. Those routes have to be the last in your routes file in order to not override the other routes.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.