Reputation: 14372
I have an Post
model with a category
attribute and corresponding PostsController
.
I would like to override the default url helper to produce the folowing:
@post = Post.create(category: 'posts')
<%= link_to 'Post Link', @post %>
# /posts/1
@post = Post.create(category: 'articles')
<%= link_to 'Article Link', @post %>
# /articles/2
I would like to call the default url helper for Post
but have it create different urls based upon the category
column.
Update
I ended up overriding the url helpers:
module PostsHelper
def post_path(post, options={})
self.send("#{post.category}_path", post, options)
end
def post_url(post, options={})
self.send("#{post.category}_url", post, options)
end
end
Upvotes: 0
Views: 280
Reputation: 393
Named Routes is what you want:
get 'posts/:id', to: 'posts#<controller-action>', as: 'posts'
<%= link_to 'Post Link', posts_path(@post) %>
get 'articles/:id', to: 'posts#<controller-action>', as: 'articles'
<%= link_to 'Article Link', articles_path(@post) %>
See here: http://guides.rubyonrails.org/routing.html#naming-routes
Upvotes: 1