Mike Legacy
Mike Legacy

Reputation: 1066

Grab only text from blog post that includes image, tables, etc

I'm using Rails 4.0.0 and CKEDITOR to build out a small blog for a client, and I'm having an issue with the page that displays the ten most recent posts and a small excerpt.

If an image was inserted into the post, or a table, or any other html element, that is coming over as well.

Can I just grab the text, without image, tables, etc?

Here is my controller code:

class PostsController < ApplicationController

  before_filter :authorize, only: [:new, :create, :edit, :update]

  def index
    @posts = Post.all
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(params[:post].permit(:title, :text, :photo))

    if @post.save
       redirect_to @post
    else
       render 'new'
    end
  end

  def edit
    @post = Post.find(params[:id])
  end

  def update
    @post = Post.find(params[:id])

    if @post.update(params[:post].permit(:title, :text, :photo))
      redirect_to @post
    else
      render 'edit'
    end
  end

  def destroy 
    Post.find(params[:id]).destroy
    redirect_to posts_path
  end

  def show
    @post = Post.find(params[:id])
  end

  private
    def post_params
      params.require(:post).permit(:title, :text, :photo)
    end

end

And my view code:

<% @body_class = "blog" %>

<div class="wrap">

  <h1>Listing posts</h1>

  <p><%= link_to 'New post', new_post_path, 'data-no-turbolink' => 'false' %></p>

    <% @posts.each do |post| %>
      <div class="post" id="<%= post.id %>">
        <div class="postTitle">
          <%= post.title %>
        </div>
        <div class="postContent">
          <%= post.text.html_safe %><br/><br/>
          <%= link_to 'Show', post_path(post) %> 
          <% if current_user %>|
          <%= link_to 'Edit', edit_post_path(post), 'data-no-turbolink' => 'false' %> |
          <%= link_to 'Destroy', post_path(post), :confirm => 'Are you sure you want to delete this post?', :method => :delete %>
          <% end %>
        </div>
      </div>
    <% end %> 

</div>

Thanks all!

My last resort will be to just create a new column in the database for an "Excerpt that they can write themselves. That may be a better idea anyways.

Upvotes: 0

Views: 185

Answers (1)

Yuri Golobokov
Yuri Golobokov

Reputation: 1965

You need strip_tags plus truncate

truncate(strip_tags(post.text), length: 100, separator: ' ')

And you should save the result in before_save callback into special field you talked about for optimization.

Upvotes: 1

Related Questions