Redirect to after successful ajax form

后端 未结 3 1912
执笔经年
执笔经年 2021-02-20 12:03

I\'ve got a form with remote => true. And right now my controller looks like:

  # POST /items
  # POST /items.json
  def create
    @item = @store.items.build(pa         


        
3条回答
  •  抹茶落季
    2021-02-20 12:11

    I use a combination of Rails responders to generate my response messages and some content in my .js file.

    The content of — say update.js would look something like this:

    // Checks if the article slug has changed.
    // If it has the entire page should be reloaded at that new location.
    <%= reload_if_slug_changed @article, params[:id] %>
    
    // Displays the flash notices
    // See ApplicationHelper#js_flash_response
    <%= js_flash_response %>
    

    Where the different methods are defined in some helper (in my case my ApplicationHelper). The content of the different methods are as follows:

    def js_flash_response
      if flash.now[:notice].present?
        js = "$('#notice').html('#{flash.now[:notice]}').change();"
      elsif flash.now[:alert].present?
        js = "$('#alert').html('#{flash.now[:alert]}').change();"
      end
    end
    
    def reload_if_slug_changed object, expected_value
      "window.location.href = '#{url_for [:edit, object]}';" if object.slug != expected_value
    end
    

    The content of the flash messages are generated automatically by Rails responders and displayed with the now scope that deletes the from the flash hash, ensuring that if the user reloads (after the flash has been displayed) they will not reappear.

    I don't believe that you should ever make a form pointing to a restful create action a remote one, because you would always expect critical redirect, so in my case I only need to redirect if the url slug has changed.

    I hope that this helps. It's not a solution, but simply the way that I handled some of the same problems.

    Best regards.

提交回复
热议问题