Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rails Action not Redirecting

I have my rails create action:

 def create
    @assessment = Assessment.new(user_id: current_user.id, patient_id: params[:assessment][:patient_id], template_id: params[:assessment][:template_id])

    @answers = params[:assessment][:answers]

    if @assessment.save

       @answers.each do |question, array|
         @assessment.answers.create(question_id: question, content: array[0], tracking: array[1])
       end

      redirect_to assessments_path
    else
      render :new
    end

  end

When I post to this action, the @assessment is getting created in the database (as well as the answers), and the log shows:

Redirected to http://localhost:3000/assessments
Completed 302 Found in 54ms (ActiveRecord: 15.8ms)

But the view in my browser is not changing. How can I get it to redirect?

FYI this is how I am submitting the form data:

$("#new_assessment").find('input[name=commit]').on('click', function(e){

          e.preventDefault();
          var $inputs = $('#new_assessment :input');

          Array.prototype.clean = function(deleteValue) {
            for (var i = 0; i < this.length; i++) {
              if (this[i] == deleteValue) {         
                this.splice(i, 1);
                i--;
              }
            }
            return this;
          };

          var template_id = gon.template.id;
          var patient_id = gon.patient.id;
          var answers = {};

          $('.question').each(function() {

                  var question = $(this).find('.question-field').data('question');
                  var answer = $(this).find('.question-field').val();
                  var trackable = $(this).find('.trackable').is(':checked');

                  if (answer && answer.length > 0 && answer != "undefined") {
                    answers[question] = [answer, trackable];
                  }

          });



         $.ajax({
            url: "/assessments",
            type: "POST",
            data: {assessment:{template_id, patient_id, answers}},
            success: function(resp){
               console.log("success") },
            error: function(err) {
              console.log("error");
            }
           });



  });

Upvotes: 0

Views: 72

Answers (2)

Ankit Kalia
Ankit Kalia

Reputation: 130

In ajax call you have to use js format in controller

  render js: "window.location = '#{assessments_path}'"

Upvotes: 1

Yen-Ju
Yen-Ju

Reputation: 477

If it is an AJAX post, you cannot use Rails redirect_to. You have to use JavaScript to do the redirect. This stackoverflow question might give you the answer.

    format.html { redirect_to assessments_path }
    format.js { render :js => "window.location.href = ('#{assessments_path)}');"}

Upvotes: 0

Related Questions