Save newline in text area with Ruby on Rails

To practice Ruby on Rails, I create a blog that includes a text area (following the Mackenzie Child tutorial). When text is sent, all newlines are deleted. I know that variants of the question have already been asked, but I could not reproduce any results, despite the fact that I tried all day. I am not very familiar with jQuery.

Is there a set of steps that will save newlines?

_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 
+7
ruby ruby-on-rails textarea
source share
1 answer

Newlines are actually saved (like \r\n ), you just don't see them in your pointers / views.

In these views, call simple_format in the post.body field to replace \n with <br> s (HTML lines):

 simple_format(post.body) 

From the docs:

 simple_format(text, html_options = {}, options = {}) public Returns text transformed into HTML using simple formatting rules. Two or more consecutive newlines(\n\n) are considered as a paragraph and wrapped in <p> tags. One newline (\n) is considered as a linebreak and a <br /> tag is appended. This method does not remove the newlines from the text. 
+30
source share

All Articles