Reputation: 2343
To practice Ruby on Rails, I am creating a blog which includes a text area (following Mackenzie Child's tutorial). Unfortunately, line breaks are included every time I press enter. How can I remove the extra line breaks?
show.html.erb
<h1><%= @post.title %></h1>
<p><%= simple_format(@post.body) %></p>
_form.html.erb
<div class="form">
<%= form_for @post do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_area :body %><br>
<br>
<%= f.submit %>
<% end %>
</div>
posts_controller.rb
class PostsController < ApplicationController before_action :authenticate_user!, except: [:index, :show]
def index
@posts = Post.all.order('created_at DESC')
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :body))
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
So I type the following into the text area:
for j in 1..array.length-1
key = array[j]
i = j - 1
But this is what posts:
for j in 1..array.length-1
key = array[j]
i = j - 1
And if remove simple_format, it removes all new lines, which I don't want either.
In the developer tools:
<p>
" for j in 1..array.length-1
"
<br>
" key = array[j]
"
<br>
" i = j - 1
"
<br>
Upvotes: 0
Views: 1634
Reputation: 715
I’m going to assume, that because you are wrapping the body content in show.html.erb, that you don’t mind the data in your database but just want to clean it up to present it.
Have you tried:
<p><%= strip_tags @post.body %></p>
Upvotes: 1
Reputation: 66263
I could be misunderstanding the question, but I think you're getting confused about the purpose of simple_format
.
simple_format
takes some text that has line breaks in it and formats it as basic HTML by replacing 2 or more line breaks as paragraphs and single line breaks as <br>
tags. This is what you would use to display a post to a visitor to the blog.
When you want the text of an existing blog post in a textarea
then you want to leave the line breaks in the text intact, which is achieved using <%= f.text_area :body %>
without wrapping in a call to simple_format
.
Upvotes: 1