使用Ruby on Rails保留文本区域中的换行符

为了练习Ruby on Rails,我正在创建一个包含文本区域的博客(遵循Mackenzie Child的教程)。 提交文本后,将删除所有换行符。 我知道这个问题的变化已经被提出,但是尽管整整一天都在努力,但我无法复制任何结果。 我对JQuery不太熟悉。

是否有一组步骤可以保留换行符?

_form.html.erb







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 

实际上保留了换行符(如\r\n ),您只是在索引/显示视图中看不到它们。

在这些视图中,在post.body字段上调用simple_format以用\n (HTML换行符)替换\n s:

 simple_format(post.body) 

来自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 

tags. One newline (\n) is considered as a linebreak and a
tag is appended. This method does not remove the newlines from the text.