Rails: Remote Form in a Partial: works once , not

2019-06-27 07:29发布

问题:

I've been confronted to a problem this last days. I want to update an object using a remote form. I can basically update my object when I submit my form the first time, but it doesn't work the second time.

So, I have a remote form in a partial.

view/missions/_table_form.haml.erb

%tr{:class => "tr_mission_#{mission.id} tr_mission"}
  = form_for(mission, :url => mission_path(mission), :html => { :remote => true , :method=> :put, :format => :js, :multipart => true, :class => "my_remote_form" }) do |f|
    = f.text_area :description,  :size => "220x6", :class => "fill_data"
    = f.submit  'Update', :class => "btn btn btn-inverse", :disable_with => "updating..."

This is my controller /app/controllers/missions_controller.rb

def update
    @mission = Mission.find(params[:id])
    respond_to do |format|
        format.html {
           render :action => "edit"
        }
        format.js {}
    end
  end

This is /missions/update.js.erb:

$('.tr_mission_<%= @mission.id %>').replaceWith('<%= escape_javascript( render :partial => "table_form", :locals => {:mission => @mission}).html_safe  %>');

The update of my object works once, not twice, On the firebug console, I can see that the type of my form is the first time: text/javascript and the next time it turns on text/html...

Thank you for your helps.

回答1:

For First time the javascript is freshly loading in your page. So it will work. Next time your javascript is not working means you may be added your script code inside document.ready.......

For this issue you have two solutions:

  1. You need to call javascript files once again on each update time.
  2. You Specify your update calls in particular javascript function and you must call that javascript function on each update fires in your page.