Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
rails - Update View when Form is Submitted without Refreshing the Page

I'm building a Rails app in which there are exercises and user_answers. When the user sees an exercise, there is a form that he can submit with the answer he thinks is right.

When submitting, I want the same view to be shown, without a refresh, but with a new div which has the solution of the exercise. The view shown is the exercises/show and a form rendered in the user_answers folder. Right now, my code looks like this:

exercises/show.html.erb

    <div class="container exercise-page">
  <h2 class="exercise-title">Exercício <%= @exercise.id %> de <%= @exercise.category %> - <%= @exercise.sub_category %></h2>

<br>
  <%= render 'user_answers/user_answer_form' %>

  <br>
  <div id="solution_exercise">
  </div>

user_answers/_user_answer_form.html.erb

  <%= simple_form_for [@exercise, @user_answer], authenticity_token: true, remote:true, :method => 'POST', :html=> { class: 'col-xs-12 col-sm-12 col-lg-3 mx-auto text-center list-group', id:"form"} do |f| %>
  <%= f.simple_fields_for :answers, include_id: false do |answer| %>
    <%= f.input_field :answer, 
        label: 'Answer',
        as: :radio_buttons,
        class: 'form-check-input',
        :item_label_class => 'list-group-item',
        name: 'answer',
        collection: @answers, label_method: :answer %>
        <br>
    <%= f.submit 'Submit Answer!', class: "btn btn-outline-success", id: "submit" %>
  <% end %>

user_answers_controller.rb

def create
    @user_answer = UserAnswer.new(user_answer_params)
    @answers = Exercise.find(params[:exercise_id]).answers
    @exercise = Exercise.find(params[:exercise_id])
    @user_answer.exercise = @exercise
    @user_answer.answer = @exercise.answers.find(params[:answer])
    @user_answer.user_id = current_user.id
    @user_answer.save
    
    respond_to do |format|
        format.js
    end     
end

user_answers/create.js.erb

solution = document.querySelector("solution_exercise")
solution.innerHTML = '<%= j render partial: "solution" %>'

user_answers/_solution.html.erb

<p>Your answer: <%=current_user.user_answers.last.answer.answer%></p>

The error:

enter image description here

Does someone know what I'm doing wrong?

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!