12

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.

Jack
  • 1,125
  • 1
  • 13
  • 29
  • You could possibly use javascript to solve something like this today (i.e. 2021) - this might entail an extra dependency, but is largely seamless if you are using Stimulus JS with Webpacker on Rails: here is an example of the types of things that are possible - it might suit your needs: https://stimulus-components.netlify.app/docs/components/stimulus-read-more/ – BenKoshy Feb 16 '21 at 00:18

3 Answers3

29
<%= 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

Damien
  • 26,933
  • 7
  • 39
  • 40
14

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.

miaout17
  • 4,715
  • 2
  • 26
  • 32
7

Use truncate helper

truncate(text, :length => 100)

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

railscard
  • 1,848
  • 16
  • 12