Rail save to database encoded html and show in view

I have a made with form_for with a textarea. After I press SEND button , with ajax gets the value and go to create method witch is:

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

The problem is that if I type alert("ok") the inserted data on the database is not encoded. So next time when I refresh the page a OK popup appear. How can I encode?

Upvotes: 2

Views: 58

Answers (1)

Tim Kretschmer
Tim Kretschmer

Reputation: 2280

use rails sanitizer helpers

=simple_format @question.question_text
=h @question.question_text

btw: instead of

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>" } 

you can do

html: render_to_string "path/to/template"

which is way more cool and flexible. can use whatever you want in your template, regular hml stuff for example

Upvotes: 1

Related Questions