开发者

default URL for a model in rails?

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/po开发者_如何学Csts/222

How can I do it? Thank you


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)


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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜