[英]undefined method for nil:NilClass error in Rails
我在Rails控制器中定義了以下實例變量:
class PagesController < ApplicationController
def about
@story, @story2 = Post.tagged_with("test").all(order: "RANDOM()", limit: 2)
end
end
但是,當我嘗試在視圖頁面中使用變量時,出現以下錯誤: NoMethodError in Pages#about
: NoMethodError in Pages#about
undefined method user for nil:NilClass
認為沒有任何作用。 這是視圖中引發錯誤的部分:
<% if @story.user.photo_file_name.present? %>
<%= image_tag @story.user.photo.url(:avatar) %>
<% else %>
<%= image_tag('avatar.png', :size => "50x50") %>
<% end %>
我在控制器中看不到變量定義有問題。 是什么導致錯誤?
謝謝!!
似乎您沒有任何帖子,因此@story
為nil
您的實例變量不會被填充,因此您的查詢一定不能返回任何內容。 數據庫中沒有與您要查找的內容匹配的內容,或者請求格式錯誤。
如果您確定數據庫中有匹配的記錄,我可以嘗試使用它作為替代方法以查看是否有幫助:
@story, @story2 = Post.tagged_with("test").order("RANDOM()").limit(4)
正如其他人已經告訴過您的那樣,您代碼中的某些內容將獲得nil值,而實際上不應該。 使用撬來調試代碼,
binding.pry
在開始PagesController#about
並開始播放
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.