Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a blog in rails -- how do I limit text and put a "read more" link to show the rest of post?

I'm building a blog using RoR. I have the index.html.erb page for the posts showing all of the posts. It displays all of the posts and all of their content. I'd like to limit the content that is shown to a certain number of characters and then put a "read more" link to go to the show page for that individual blog post. Any help with how to do this? Thanks.

like image 698
Jack Avatar asked Nov 25 '11 02:11

Jack


2 Answers

To show a certain number of characters, you can use truncate helper method to truncate your article.

truncate("Once upon a time in a world far far away")
# => "Once upon a time in a world..."

If you also have question about "read more" link, please read "resource routing" section in Rails Routing from the Outside In. You should show all your posts in index action (probably with pagination), and show single post in show index. Truncate the post in the index view, and show the full post in show view.

like image 51
miaout17 Avatar answered Oct 16 '22 18:10

miaout17


<%= truncate post.content, length: 160 %>
<%= link_to 'read more', post %> 

See the documentation for truncate: http://api.rubyonrails.org/classes/String.html#method-i-truncate

like image 29
Damien Avatar answered Oct 16 '22 19:10

Damien