jquery - Rail 保存到数据库编码的 html 并显示在 View 中

标签 jquery ruby-on-rails ruby

我用 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/

相关文章:

javascript - Jquery - 在滚动到 50% 时将 DIV 旋转 X 度

jquery - 移动 Safari 上高度为 100% 的 Div

ruby-on-rails - 设计两个模型

ruby-on-rails - Rails 表单创建在验证错误后提交更新

ruby - 无法为 Rails 应用程序创建数据库

javascript - 在 Canvas 上循环绘制图像不起作用

ruby-on-rails - 尽管有 heroku 工具带,但 Heroku gem 还是出现了

ruby-on-rails - 在 Rails 2 应用程序中使用 ssl_requirement 强制使用 SSL

ruby - tcp 客户端无法从 eventmachine 接收数据

Javascript 在一段时间内按下按钮