简体   繁体   中英

Rails create without redirect or refresh

I've got a javascript script on a view that submits data to a rails controller via a post method :

$.post("/user_answers?user_answer[question_id]=" + gon.questions[questionNum]["id"] + "&correct=true")

and basically the controller takes this post and updates or creates a new user_answer.

def create
  @user_answer = current_user.user_answers.find_or_initialize_by(answer_params)    
  # Handles box assignment based on correct or wrong answer
  if params[:correct] == "true"
    @user_answer.box = 1
  elsif params[:correct] == "false"
    @user_answer.box = 2
  end
  @user_answer.save
end

This works perfectly, except I noticed that the controller tries to redirect to user_answers/create and returns an error because that doesn't exist. This doesn't affect the user's experience at all, but it does make an extra request to the server for no reason.

The thing is, I don't want to redirect to anything or refresh to anything, because the post just needs to update the record. The view updates itself using Javascript. How do I remove the default redirect_to action in .save or .create?

You can throw in

return false

wherever you want the code execution in your action to stop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM