我收到了这个错误:
NoMethodError in Videos#index
Showing /rubyprograms/dreamstill/app/views/videos/index.html.erb where line #12 raised:
undefined method `upvoted_videos' for nil:NilClass
Extracted source (around line #12):
9: <div class="home_options">
10: <ul class="home_options_list">
11: <li> <%= link_to "Top Songs", videos_path, :class => "top_songs chosen_home_option" %> </li>
12: <li> <%= link_to "#{pluralize(current_user.upvoted_videos.count, 'Upvoted Song')}", upvoted_videos_path, :action => "upvoted_songs", :class => "upvoted_songs" %> </li>
这是我的用户模型:
def upvoted_videos
self.voted_videos.where("value = 1")
end
答案 0 :(得分:2)
由于您尝试在nil对象上调用upvoted_videos
,因此抛出错误。这意味着current_user
为零。在调用current_user
upvoted_videos
是否为零
答案 1 :(得分:1)
每当你得到一个NoMethodError
总是只是去检查原因,它说你试图在nil
对象上打电话。
这意味着在执行此操作之前,您不能拥有current_user
,因此请确保有人登录。
同样优秀的做法是对这样的函数进行回退,比如a
<% unless current_user.nil? %> ...(Do function here)... <% end %>
或视图中的某些内容