我用 form_for 制作了一个文本区域。在我按下 SEND 按钮后,使用 ajax 获取值并去创建方法 witch 是:
def create
@question = Question.create(question_params)
respond_to do |format|
if @question.save
#format.json { render :json => @question.to_json, :status => 202 }
format.html { render :html => "<div class='col-md-12 portfolio-item' id='question_#{@question.id}'> #{@question.question_text} at <i>#{@question.created_at}</i></div>" }
else
format.json { render :json => @question.errors, :status => 403 }
end
end
end
def question_params
params.require(:question).permit(:question_text)
end
问题是,如果我键入 alert("ok"),数据库中插入的数据未编码。所以下次当我刷新页面时,会出现一个 OK 弹出窗口。我该如何编码?
最佳答案
使用 Rails sanitizer 助手
=simple_format @question.question_text
=h @question.question_text
顺便说一句: 而不是
format.html { render :html => "<div class='col-md-12 portfolio-item' id='question_#{@question.id}'> #{@question.question_text} at <i>#{@question.created_at}</i></div>" }
你可以做到
html: render_to_string "path/to/template"
这更酷更灵活。可以在模板中使用任何你想要的东西,例如常规的 hml 东西
关于jquery - Rail 保存到数据库编码的 html 并显示在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32461120/