How can I reload the current page in Ruby on Rails?

时光总嘲笑我的痴心妄想 提交于 2019-11-29 00:18:41

问题


I currently have a login popup in my header bar which is on every page in my website. I want to be able to reload the current page that the person is on after a successful login. How do I do this in the controller?

def create
  #declaring and defining user variable stuff
  if user.save
    #reload current page <--how do I do this?
  end
end

Thanks


回答1:


For my application, I use redirect_to :back and it does the trick. However, I doubt this might have an error in a non general use case(s) (user came from a special page?) but i haven't found it so far in my app.




回答2:


If you're looking for a way to get the page to refresh (typically redirect_to :back) with an XHR request, you don't have to look for a way to change the response type - just tell the page to reload with inline JS.

format.js {render inline: "location.reload();" }

Like Elena mentions, this should go in a respond_to block, like so:

respond_to do |format|
  format.js {render inline: "location.reload();" }
end



回答3:


In Rails 5 redirect_to :back is improved by:

    redirect_back(fallback_location: root_path)



回答4:


Archonic's answer above worked for me. However, in Rails 3, I had to place this in a respond_to block in order to avoid an 'ArgumentError (too few arguments)' error:

respond_to do |format|
  format.js {render inline: "location.reload();" }
end



回答5:


Since Rails 5 (or maybe older versions), you have a request.referrer method. You simply redirect from controller to referrer and it opens the page where request came from.

redirect_to request.referrer, notice: "You're being redirected"




回答6:


Rails 5 introduced alternative function:

redirect_back(fallback_location: root_path)

It redirect back whenever the HTTP_REFERER is known. Otherwise it redirects to the fallback_location.

The redirect_to :back is deprecated in Rails 5.0 https://github.com/rails/rails/pull/22506 and removed since Rails 5.1



来源:https://stackoverflow.com/questions/7465259/how-can-i-reload-the-current-page-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!