使用Ruby on Rails在文本区域中保留换行符
问题描述:
为了练习Ruby on Rails,我创建了一个包含文本区域的博客(遵循Mackenzie Child's tutorial)。提交文本时,所有换行符都被删除。我知道这个问题的变化已经被问到了,但是尽管整整一天都在尝试,我仍然无法复制任何结果。我对JQuery不是很熟悉。使用Ruby on Rails在文本区域中保留换行符
是否有一组步骤可以保留换行符?
_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
答
换行符实际上被保存(如\r\n
),只是你没有看到他们在您的索引/节目的看法。
在这些意见,请致电simple_format
您post.body
场<br>
S(HTML换行符),以取代\n
S:
simple_format(post.body)
从文档:
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.
太谢谢你了!我花了整整一天的时间来解决这个问题。我无法相信这个解决方案很简单。 – jro 2015-02-08 19:27:12
每次我输入时,都会留下换行符。无论如何要避免这一点? – jro 2015-02-09 01:52:17
@JonRoby对不起,我不确定你的意思。如果您有新问题,请通过单击[提问](http://stackoverflow.com/questions/ask)按钮来提问,并描述显示相关代码的问题。如果有助于提供上下文,请包含此问题的链接。 – 2015-02-09 03:42:04