简体   繁体   中英

Previous page after updating rails

I am trying to go back to the previous page after updating a link. Here is my link controller:

def update

  if @link.update(link_params)
    redirect_to :back
  else
    format.html { render :edit }
    format.json { render json: @link.errors, status: :unprocessable_entity }
  end
end

Although the link does update, it the page only refreshes, instead of going back to the previous page. Could someone help point out what I am doing wrong? Thanks!

Referrer

Each time you load a controller action in your application, you'll get a request object , which should have the referer attribute :

def update

  if @link.update(link_params)
    redirect_to request.referer 
  else
    format.html { render :edit }
    format.json { render json: @link.errors, status: :unprocessable_entity }
  end
end

The problem is that you are sending a request from your browser in a way that it wants to handle the response as if you were going to a new page. redirect_to :back simply tells rails to send the referrer as the redirect URL. If the code read redirect_to 'http://google.com' you would expect the browser to go to google.com, would you not? The correct thing to is to make an asynchronous call using javascript and use javascript to go back in the event of success.

How this happens depends on which JavaScript library you are using. Simply make the call, and in your success function, call window.history.back() and the browser will go back.

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