Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
7 Posts
Read more link


Is there an easy way to create a read more link? I mean, when you look at this http://workingwithrails.com/home -> check Featured Job, you see the 3 dots standing there. There I'd like to add a link "read more" to show the full article.

  • Is it easy to create a shorter version of a text? (With a limit or so?)
  • How can you do this using ruby?


model.attribute[0,50] would give you the first 50 chars from the attribute field (assuming it's a string). So, if you had a page that you wanted to display a bunch of shortened text versions (a la a wordpress index that has just a few sentences from each post), you could do

link_to( "#{model.attributes[0,50]}... read more", read_more_path)

There is also "truncate":http://api.rubyonrails.com/classes/ActionView/Helpers/TextHelper.html#M001541 in ActionView::Helpers::TextHelper

truncate("And they found that many people were sleeping better.", :length => 25, "(clipped)") And they found that many (clipped)

So you can do:

link_to truncate(model.text, :length => 50, "(read more)"), read_more_path

I'm pretty sure you would want to do:

truncate(model.text, :length => 50, link_to('(read more)', read_more_path))

Otherwise, the entire preview text would be a hyperlink.

Thanks for the solutions. Would this be possible to do it with some kind of javascript? So that you don't have to reload the page, that the content just slides in?

You're correct Ernie, I should have double checked. My example above would have everything as a hyperlink - you'd want to remove the model.attributes[0,50] from the link_to function. Or, just use truncate.

Look into link_to_remote instead of link_to for an ajax slide in. You'll need to do a bit of dom manipulation to remove the read more... and slide in the real text, but it should be doable.

Ok thanks that will work:)

Thanks for your help and time

7 Posts
Login to add your message