I have the following route in my Rails3 project:
match "/blog/:permalink" => "posts#show", :as => :post
When I link to my post through a view as such:
<%= link_to @post.title, post_path(@post) %>
The id of the post is passed into the post_path helper (even though my route specifies the permalink is passed.
How do I force the post_path to send in the permalink instead of the id of the post?
I can explicitly call post_path(@post.permalink)
but that seems dirty.
Am I missing something in my route?
Thanks!
Define a to_param
method on the model that returns the string you want to use.
class Post < ActiveRecord::Base
def to_param
permalink
end
end
See this page, this Railscast, (and of course Google) for more info.
[Edit]
I don't think Polymorphic URL Helpers are smart enough to handle what you want to do here. I think you have two options.
1. Use a special named route and pass in the parameter similar to your question and Jits' answer.
match "/blog/:permalink" => "posts#show", :as => :post
and link to it
<%= link_to @post.title, post_path(:permalink => @post.permalink) %>
2. Create a new helper that generates the URL for you
match "/blog/:permalink" => "posts#show", :as => :post_permalink
and a helper
def permalink_to(post)
post_permalink_path(post.permalink)
end
and in your views
<%= link_to @post.title, permalink_to(@post) %>