[英]error rendering a flash message with jquery ajax in ruby on rails app
這是我得到的錯誤:
ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
它在部分視圖中引用此代碼:
<% flash.each do |key, value| %>
<div class="<%= key %>"><%= value %></div>
<% end %>
我在micropost控制器中設置了Flash消息:
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
這是我在views / microposts / create.js.erb中的js代碼:
$('div.notice').append('<%= render 'shared/flash' %>');
而且部分內容會在我的應用程序布局中動態呈現:
<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>
如何解決此錯誤? 我究竟做錯了什么?
問題出在您的部分文件的命名上。
Rails試圖對局部文件保持聰明,並自動公開與局部文件的文件名相同名稱的局部變量。 之所以這樣做,是因為最常見的用例是讓局部函數將HTML片段綁定到某物的實例,即:
# the following is treated as: render :partial => "frobs", :collection = @frobs
render @frobs
然后,在_frob.html.erb
部分中,有一個名為frob
的變量,該變量引用@frobs
的當前實例。
在您的情況下,這與ActionView
公開的flash
方法沖突:局部變量將始終勝過方法名稱。 嘗試將您的部分內容重命名為其他內容(即flash_message),使內容相同,然后查看是否可行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.