Trần Kim Dự
Trần Kim Dự

Reputation: 6112

ActiveRecord: limit length of text when getting records from database

I'm using Rails 5. My database is Postgres 9.4. I have a following table:

Post
id
post_title
post_content

My query for getting post is:

Post.limit(5).all

But I want each returned post should return limit content of post_content. For example, first 400 characters. I can do this by code, but I think it will be better if I can do this under database. (best is using ActiveRecord). Do we have any solution for this.

Thanks

Upvotes: 0

Views: 402

Answers (1)

Tom Copeland
Tom Copeland

Reputation: 1271

You can use a function and a column alias in a select method:

Post.select(:id, :post_title, "left('post_content', 5) as post_content")

Upvotes: 1

Related Questions