SamuraiBlue
SamuraiBlue

Reputation: 861

Rails4: How can I use truncate method for the data retrieved Model.all?

How can I use truncate method for the data retrieved all from model?

I'd like to truncate the content data in the article model like <%= truncate(content, length: 50) %>.

\views\articles\index.html.erb

<ul class="users">
  ...
  <%= render @articles %>
  ...
</ul>

\controllers\article_controller.rb

class ArticlesController < ApplicationController

  def index
    @articles = Article.all(limit: 10)
  end
  ...

article table

sqlite> .schema articles
CREATE TABLE "articles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "content" varchar(255),"user_id" integer, "created_at" datetime, "updated_at" datetime, "category_id" integer);

Upvotes: 1

Views: 291

Answers (1)

Alaa Othman
Alaa Othman

Reputation: 1149

As mentioned in the comments, since you are using

<%= render @article %>

Rails will search for an _article partial in the views/articles directory so you have to create one if you haven't created one already and it would be something like that

views/articles/_article.html.erb

<%= truncate(article.content, :length => 50) %>
.
.

Upvotes: 2

Related Questions