pratski
pratski

Reputation: 1488

How to display the first 10 characters only of a message stored in database?

In my inbox view, where I am able to list each individual message, I want to display the first 10 characters of a message if the message is larger than 10 characters or display the entire message. The user can then click on the message to view the entire message.

message.body

is where the contents of the message are stored in the database.

Upvotes: 2

Views: 3242

Answers (3)

Aryeh Beitz
Aryeh Beitz

Reputation: 2078

To have a string with a total of 10 chars (including the ... at the end)

message.body.truncate(10)

or to cut to end of last complete word

message.body.truncate(10, separator: /\s/)

Examples:

"some simple words here that is too long".truncate(23)
 => "some simple words he..." 

"some simple words here that is too long".truncate(23,separator: /\s/)
 => "some simple words..."

Upvotes: 1

Dave Sexton
Dave Sexton

Reputation: 11188

Try this:

truncate(message.body, :length => 10)

Upvotes: 9

MurifoX
MurifoX

Reputation: 15089

Use truncate. Link for the documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Upvotes: 6

Related Questions