I just updated to Rails 3.1 and a typical ajax form to create a model object is producing the following error on success: ActionView::Template::Error (undefined method gsub' for #<ActionDispatch::Flash::FlashHash:0x00000102b73b78>):
The create action is going well, the data is submitted to the database, but the page does not change and the js doesn't execute. the js DOES work if there's an error, producing the error message as expected.... So only the success is producing the error and failing to execute the js.
Here's 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's the stack trace when a new contact is saved:
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 can see what I'm missing here. Thank a bunch.
Rails has changed the way some things work in 3.1, from what I understand Rails 3.1 is not using Hash for the FlashHash any more and they now are basing it off of Enumerable. Here is an answer that goes into more detail. You should be able to use:
flash.discard(:notice)
Instead of the old:
flash.delete(:notice)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With