1

I have a class Post

I want the default URL of each posts to be http://domain.com/9383 instead of http://domain.com/posts/9383

I tried to fix it in the routes. I manage to accept domain.com/222 but if I use <%= url_for(@posts) %> I still get domain.com/posts/222

How can I do it? Thank you

3 Answers 3

5

You can't change the behaviour of url_for(@post) with routes. url_for will assume a map.resources setup if an ActiveRecord instance is passed to it.

You should rather do this:

# routes.rb
map.post ":id", :controller => "posts", :action => "show"

# named route
post_path(@post)

# full link_to
link_to @post.title, post_path(@post)
0

If you're using url_for, there's no way to tell it to omit the /posts/ section. I think you would need to create helper, maybe in application_helper.rb

def post_url(post)
  "/#{post.id}"
end
0

Overriding url_for seems to not be considered a best practice in Rails, although it seems terribly convenient to me. Here's a description of how to do it by customizing ApplicationController: http://arjanvandergaag.nl/blog/generating-fancy-routes-with-rails.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.