Domanda

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.

È stato utile?

Soluzione

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...

Altri suggerimenti

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!

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top