Rails 3.1 AJAX form - "ActionView :: Template :: Error (undefined method` gsub 'for # <ActionDispatch :: Flash :: FlashHash: 0x00000102b73b78>): "
I just upgraded to Rails 3.1, and a typical ajax form to create a model object results in the following error: ActionView::Template::Error (undefined method gsub' for #<ActionDispatch::Flash::FlashHash:0x00000102b73b78>):
The create action happens well, the data is transferred to the database, but the page does not change and js is not executed. js DOES work if there is an error, creating an error message as expected .... Thus, only success causes an error and does not execute js.
Here is my code:
Controller:
def create @contact = Contact.new(params[:contact]) respond_to do |format| if @contact.save flash[:notice] = "Welcome!" format.html format.js else format.html { render 'pages/home'} format.js end end end view form
<div id="contact_notice"></div> <%= form_for @contact, :remote => true do |f| %> <%= f.text_field :email, :id => 'email', 'data-default' => 'Sign up to join the beta!' %><%= f.submit "Submit", :id => 'submit' %> <% end %> /views/contacts/create.js.erb
<% if @contact.errors.any? %> // Create errors var errors = $('<div class="flash notice"></div>'); <% @contact.errors.full_messages.each do |error| %> errors.append('<%= escape_javascript( error ) %>'); <% end %> // Display errors $("#contact_notice").html(errors); <% else %> // Display success (clearing any errors) $("#contact_notice").html('<div class="flash notice"><%=escape_javascript(flash.delete(:notice)) %></div>'); <% end %> And here is the stack trace while saving a new contact:
Rendered contacts/create.js.erb (0.6ms) Completed 500 Internal Server Error in 13ms ActionView::Template::Error (undefined method `gsub' for #<ActionDispatch::Flash::FlashHash:0x000001042b1970>): 12: <% else %> 13: 14: // Display success (clearing any errors) 15: $("#contact_notice").html('<div class="flash notice"><%= escape_javascript(flash.delete(:notice)) %></div>'); 16: 17: <% end %> app/views/contacts/create.js.erb:15:in `_app_views_contacts_create_js_erb__3535867194219445180_2168748520' app/controllers/contacts_controller.rb:6:in `create' Let me know if you see what I'm missing here. Thanks a lot.
Rails has changed how some things work in 3.1, from what I understand, Rails 3.1 does not use Hash for FlashHash , and now they base it on Enumerable . Here is the answer that goes in more detail. You should be able to use:
flash.discard(:notice) Instead of the old:
flash.delete(:notice)