如何修复“NoMethodError”异常?

时间:2011-04-12 17:19:54

标签: ruby-on-rails ruby debugging ruby-on-rails-3

我收到了这个错误:

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

2 个答案:

答案 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 %> 或视图中的某些内容