2016-04-18 42 views
2

我一直收到的Users#show用戶中的NoMethodError#show on rails項目

undefined method `downcase' for nil:NilClass 

我不明白嘗試使用gravatar時出現錯誤的位置。我發佈了相關代碼以幫助解決我的問題。有什麼我失蹤?


show.html.erb

<h1 align="center"> Welcome to <%= @user.username %>'s page</h1> 
<div class="row"> 
    <div class="col-md-4 col-md-offset-4 center"> 
     <%= gravatar_for @user %> 
    </div> 
</div> 
<h4 align="center"><%= @user.username %>'s articles</h4> 

users_controller.rb

class UsersController < ApplicationController 

    def new 
    @user = User.new 
    end 

    def create 
    @user = User.new(user_params) 
    if @user.save 
     flash[:success] = "Welcome to the alpha blog #{@user.username}" 
     redirect_to articles_path 
    else 
     render 'new' 
    end 
    end 

    def edit 
    @user = User.find(params[:id]) 
    end 

    def update 
    @user = User.find(params[:id]) 
    if @user.update(user_params) 
     flash[:success] = "Your account was updated successfully" 
     redirect_to articles_path 
    else 
     render 'edit' 
    end 
    end 

    def show 
    @user = User.find(params[:id]) 
    end 

    private 

    def user_params 
     params.require(:user).permit(:username, :email, :password) 
    end 
end 

application_helper.rb

module ApplicationHelper 
    def gravatar_for(user) 
     gravatar_id = Digest::MD5::hexdigest(user.email.downcase) 
     gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}" 
     image_tag(gravatar_url, alt: user.username, class: "img-circle") 
    end 
end 
+0

你以下任何手冊或書嗎? –

+0

@DharmeshRupani在線講座視頻 –

+0

檢查您的用戶的電子郵件是否存在。錯誤看起來像是價值:電子郵件是無用的。 –

回答

2

的錯誤是在gravatar_for方法的第一行。 user.email爲零,所以當它試圖在無對象上調用downcase時會出現此錯誤。發生這種情況是因爲用戶沒有電子郵件。

在嘗試獲取他的gravatar之前,您應該檢查用戶是否有電子郵件,或通過對用戶模型進行驗證來確保每個用戶都有電子郵件。

+0

謝謝@GabrielErbetta –

2

我猜想,你在這行得到的錯誤:

gravatar_id = Digest::MD5::hexdigest(user.email.downcase) 

這將意味着user.email將返回零