error rendering a flash message with jquery ajax in ruby on rails app
Here's the error I get:
ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
It's referring to this code in a view partial:
<% flash.each do |key, value| %>
<div class="<%= key %>"><%= value %></div>
<% end %>
I set the flash message in my micropost controller:
def create
@micropost = current_user.microposts.build(params[:micropost])
respond_to do |format|
if @micropost.save
flash[:success] = "Micropost created!"
format.html { redirect_to root_path, :notice => 'success' }
format.js
Here's开发者_运维技巧 my js code in views/microposts/create.js.erb:
$('div.notice').append('<%= render 'shared/flash' %>');
And the partial gets rendered dynamically in my application layout:
<body>
<div class="container">
<%= render 'layouts/header' %>
<section class="round">
<div id= "notice"></div>
<%= yield %>
</section>
<%= render 'layouts/footer' %>
<%= debug(params) if Rails.env.development? %>
</div>
</body>
How do I fix this error? What am I doing wrong?
The problem lies in the naming of your partial file.
Rails tries to be clever with partials and automagically exposes a local variable that shares the same name as the partial's file name. It does this because the most common use-case for partials to to bind an HTML fragment to an instance of something, ie:
# the following is treated as: render :partial => "frobs", :collection = @frobs
render @frobs
Then, within your _frob.html.erb
partial, you have a variable named frob
which references the current instance from @frobs
In your case, this is colliding with the flash
method exposed by ActionView
: a local variable will always trump a method name. Try re-naming your partial to something else (ie, flash_message), keeping the content the same and see if that works.
精彩评论