After submitting a remote form with Rails, how do I redirect the user to another page?

我与影子孤独终老i 提交于 2020-01-12 09:21:45

问题


I’m using Rails 4.2.3. I want to submit a form in a modal dialog, so I have set up my form like so

<%= form_for @my_object, :remote => true do |f| %>

but if the user submits the form successfully, I would like to reload the page that invoked the modal dialog with a notice of “Saved Successfully.” I can’t figure out what I need to put in my “format.js” to make this happen. This is what I have in my controller so far …

  def create
    @my_object = MyObject.new(my_object_params)
    @current_user = User.find(session["user_id"])
    @my_object.user = @current_user
    respond_to do |format|
      if @my_object.save
        format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
        format.js   { render action: ‘../users/index’, notice: ‘Saved Successfully’, location: @my_object }
      else
        format.html { render action: "index" }
        format.js   { render json: @my_object.errors, status: :unprocessable_entity }
      end
    end
  end

Right now, a successful submission results in a 500 error complaining about missing partials when I try and execute the above. Pretty sure what I have is wrong anyway.


回答1:


You can do the following:

#app/controllers/redirect.rb
...

format.js { render js: "window.location='#{url.to_s}'" }

...

If you like keeping things separated, just put format.js in your controller and do the javascript redirect in your view (redirect.js.erb)

In both cases, just set flash[:notice] to whatever you need before redirecting.




回答2:


redirect_to events_path, format: 'js'

For this you will need to have events/index.js.erb in your file structure.




回答3:


If you are redirecting anyway, you might as well avoid the remote/AJAX call, and just redirect from the create action.

<%= form_for @my_object do |f| %>

and

def create
  @my_object = MyObject.new(my_object_params)
  ...
  redirect_to some_path
end



回答4:


If you have want to redirect it after successfully create/updated and just use .html method. Otherwise just use JS option like in this LINK.

  def create
    @my_object = MyObject.new(my_object_params.merge(user: User.find(session["user_id"])))
    respond_to do |format|
      if @my_object.save
        format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
      else
      ....
      end
    end
  end



回答5:


That will help you, from your controller

render :js => "window.location = '/jobs/index'"



来源:https://stackoverflow.com/questions/37492886/after-submitting-a-remote-form-with-rails-how-do-i-redirect-the-user-to-another

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