1

I'm still very much a novice and can't figure out how to get my blog titles to link to the full post. I'm using the friendly id gem and built this basic blog following the Getting started instructions at http://guides.rubyonrails.org/getting_started.html

Below is my current code which converts the title into a link but all titles are continuing to link to the index page for posts.The linkable title should point to something similar to this example:

example.com/posts/my-first-blog-post

<h1>The Blog!</h1>
  <div class="container"> 
    <div class="row">
      <div class="col-md-1">
        <% @posts.each do |post| %>
          <h2><%= link_to post.title %></h2>
          <P><%= truncate (post.body), :length => 250 %></p>
        <% end %>
      </div>
    </div>
  </div>

I would greatly appreciate any help getting these title to link to the link name created using friendly id. If it makes any difference the slug is generated from the title and I did add and save the slug for all previously published blog post when I wasn't using friendly id.

Thank you in advance for the help.

Kevin Dark
  • 2,139
  • 5
  • 22
  • 23
  • All three answers below solved the issue. Thank you for the help. Up voted all three since I couldn't accept all as successful answers. – Kevin Dark Mar 17 '14 at 00:42

3 Answers3

3

The method signature (the way you use it) is:

 link_to text_to_display, path

If you follow Rails standards, you should do:

link_to post.title, post_path(post.slug)

Actually .slug is not required because FriendlyId overrides the to_param method in your model.

So you can do:

link_to post.title, post_path(post)

Or even

link_to post.title, post

Up to you...

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • I don't understand this is accepted as "best" answer, as the use of post.slug is not necessary, and also nowhere mentioned in the gem's documentation. For me, using it this way, degrades the friendly_id solution – Danny Mar 17 '14 at 05:52
  • How could this be written even shorter? – Danny Mar 17 '14 at 07:17
  • @Danny, well, you did add the one... was not well awake. Cheers neighbour! – apneadiving Mar 17 '14 at 07:23
  • We're indeed neighbours! Sorry about the -1. Didn't know it was only for wrong answers! – Danny Mar 17 '14 at 07:24
  • No big deal :) actually almost nobody upvotes, so downvotes are a bit upsetting – apneadiving Mar 17 '14 at 07:28
2

In your model, you should have something like

  friendly_id :title, use: :slugged

Your link should simply be

link_to post.title, post

You don't have to introduce the "slug" in your views. Simply updating the model will do!

Danny
  • 5,945
  • 4
  • 32
  • 52
1

One way we like to use is to not include the attribute of the element:

<%= link_to post.title, post_path(post) %>

If you have friendly_id set up in your model, this should work automatically

Richard Peck
  • 76,116
  • 9
  • 93
  • 147