错误:未定义的方法`avatar?'为零:NilClass

时间:2015-06-30 18:05:03

标签: ruby-on-rails ruby

我在rails应用程序中收到以下错误。

错误:

NoMethodError in Statuses#index

显示C:/Users/Arvind/project/book/app/views/statuses/index.html.erb第12行引发:

未定义的方法`头像?'为零:NilClass

Rails.root:C:/ Users / Arvind / project / book应用程序跟踪|框架跟踪|完整跟踪

app / helpers / applicationhelper.rb:28:in avatar_profile_link' app / views / statuses / index.html.erb:12:inblock in _app_views_statuses_index_html_erb__844883668_70166988' app / views / statuses / index.html.erb:9:in _app_views_statuses_index_html_erb ___ 844883668_70166988'应用程序/控制器/ statuses_controller.rb:13:inindex'

我的user.rb

 attr_accessible  :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :profile_name, :full_name, :avatar

has_attached_file:avatar,style:{large:" 800x800>",medium:" 300x200>",small:" 260x180>",thumb :" 80x80#" }

  def self.get_gravatars
     all.each do |user|
       if !user.avatar?
       user.avatar = URI.parse(user.gravatar_url)
            user.save
                print "."
              end
         end
     end 

我的application_helper.rb

def avatar_profile_link(user, image_options={}, html_options={})

avatar_url = user.avatar? ? user.avatar.url(:thumb):nil

link_to(image_tag(avatar_url, image_options),   profile_path(user.profile_name), html_options)

我的lib / task / gravatars,rake

desc "Import avatars from user's gravatar url"
   task :import_avatars => :environment do
      puts "Importing avatars from gravatar"
         User.get_gravatars
            puts "Avatars updated."
      end

我将我的头像更新为gravatar

$rake import avatar

将头像导入gravatar

.....阿凡达更新。

我的git存储库位于:https://github.com/sarahgupta022/book.git

谢谢!

2 个答案:

答案 0 :(得分:1)

问题出在avatar_profile_link方法的/app/helpers/application_helper.rb中,你必须检查用户是否为零。替换为此代码:

def avatar_profile_link(user, image_options={}, html_options={})
  avatar_url = nil
  unless user.nil?
    avatar_url = user.avatar? ? user.avatar.url(:thumb) : nil
    link_to(image_tag(avatar_url, image_options), profile_path(user.profile_name), html_options)
  end
end

答案 1 :(得分:1)

错误消息指出:

Question

undefined method `avatar?' for nil:NilClass 辅助方法接受avatar_profile_link参数。 user的值在发生错误时为user

看看你的git repo,最有可能的部分是:

nil

至少有一个<% @statuses.each do |status| %> <% if can_display_status?(status) %> <div class="status media"> <%= avatar_profile_link status.user, {}, class: 'pull-left' %> 的用户为status。根据您分享的内容,我们可以看到这一点。