drpepper
drpepper

Reputation: 165

Hard coding routes in Rails

Let's say I have this:

<%= link_to "My Big Link", page_path(:id => 4) %>

And in my page.rb I want to show urls by their permalink so I use the standard:

 def to_param
    "#{id}-#{title.parameterize}"
 end

Now when I click "My Big Link" it takes me to the correct page, but the url in the address bar does not display the desired permalink. Instead it just shows the standard:

wwww.mysite.com/pages/4 

Is this because I hard-coded an id into the page_path? It also does not work if I use straight html like..

<a href="/pages/4">My Big Link</a>

I would appreciate it if anyone could verify this same behavior and let me know if this intended or not. I need the ability to hard code :id's to specify exact pages...

Upvotes: 3

Views: 1626

Answers (3)

drpepper
drpepper

Reputation: 165

UPDATE TO MY QUESTION ---------------------->

Thanks all for the answers. This was kind of a one off situation. My solution was to simply go with html:

<a href="/pages/4-great-title-here">My Big Link</a>

Which produced the desired:

wwww.mysite.com/pages/4-great-title-here

I didn't want to loop through page objects and waste a call to the database for this one link. Much appreciated for all the answers though!

Upvotes: -1

reto
reto

Reputation: 16732

Just use page_path(page). I guess the path helpers don't access the database themself (which is good), but if they are being supplied with an object and that object has a to_param method this method is being used to generate an identifier.

<%= link_to "My Big Link", page_path(page) %>

Upvotes: 5

Toby Hede
Toby Hede

Reputation: 37133

It's because you are specifying the id:

page_path(:id => 4)

You could specify the path you want in this method:

page_path(:id => "#{id}-#{title.parameterize}")

Where have you defined the to_param method? In the model?

Upvotes: 2

Related Questions