AJAX in Rails: Show model#new form after completing a model#update

前端 未结 1 735
孤城傲影
孤城傲影 2021-02-11 03:54

I have an account setup wizard in Rails in which I\'m showing a list of companies. When a company\'s details are updated via AJAX, everything works perfectly. However, after a s

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-11 04:47

    Yea, using ajax is a good thing to do in this case. As posted, a company's details are successfully updated via ajax.

    What you can do is render a json in update action if the current update is successful, and pass the new form as json.

    def update
        @company = Company.find(params[:id])
        respond_to do |format|
        if @company.update_attributes(params[:company])
          format.json { render json: { success: true, html: render_to_string('_form.html.slim', layout: false) } }
          format.html { redirect_to @company, notice: 'Company was successfully updated.' }
        else
          ...
    

    You can access the json in your js and replace the current form element.

    $('#company_form').live 'ajax:success', (event,data) ->
        $('#current_company_form').html(data.html) if(data.success == true)
    

    Let me know if this helps.

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