[英]Rails 3 render partial error
我有一個使用局部的Rails應用,在開發中一切正常,但是在生產中我遇到了錯誤
我們很抱歉,但有些不對勁。
我們已收到有關此問題的通知,我們將盡快對其進行研究。
我檢查了production.log文件,這是我收到的錯誤
ActionView :: Template :: Error(NilClass:Class的未定義方法“ model_name”):
這是引起問題的線路
<%= div_for blog do %>
這是什么導致該文件
<%= render :partial => 'blogs/blog', :locals => {:blog => @profile.blogs.last}%>
這是整個錯誤
ActionView::Template::Error (undefined method `model_name' for NilClass:Class):
1: <%= div_for blog do %>
2: <p>
3: <b>Title:</b>
4: <%= blog.title %>
app/views/blogs/_blog.html.erb:1:in
app/views/profiles/show.html.erb:22:in
關於如何解決此錯誤的任何想法?
您實際上是在調用nil.last
,這將引發此類錯誤。
僅在 @profile
包含博客時, 才使用條件渲染部分內容:
<%= render(:partial => 'blogs/blog', :locals => {:blog => @profile.blogs.last}) if @profile.blogs.present? %>
或者,我將使用部分方法。 您認為:
<%= blogs_or_message %>
在部分中:
def blogs_or_message
if @profile.blogs.present?
render(:partial => 'blogs/blog', :locals => {:blog => @profile.blogs.last})
else
"No blogs found" # <= simple error message instead of nothing
end
end
我猜想Rails不是很聰明,如果blog
為nil
,則跳過該DIV。 以下是一些可能的解決方法:
如果您真的只想呈現一個博客:
<% div_for(@profile.blogs.last) do %>
...whatever...
<% end if @profile.blogs.last %>
或者,如果您希望每個博客都具有DIV,則不需要使用條件,因為@profile.blogs
將為您提供一個空數組,Rails知道該怎么做:
<% div_for(@profile.blogs) do %>
...whatever...
<% end %>
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.