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

前端 未结 5 607
面向向阳花
面向向阳花 2021-02-10 17:47

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| %>
         


        
相关标签:
5条回答
  • 2021-02-10 18:22

    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.

    0 讨论(0)
  • 2021-02-10 18:34

    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
    
    0 讨论(0)
  • 2021-02-10 18:35

    That will help you, from your controller

    render :js => "window.location = '/jobs/index'"
    
    
    0 讨论(0)
  • 2021-02-10 18:42

    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
    
    0 讨论(0)
  • 2021-02-10 18:47

    redirect_to events_path, format: 'js'

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

    0 讨论(0)
提交回复
热议问题