2013-03-18 53 views
0

我設置的gravatar並得到了它的工作我'users/*user id goes here*'. 但每當我嘗試時,它給我的錯誤使用它在dashboard/index這是的Gravatar - 未定義的方法「郵件」的零:NilClass

Undefined method 'email' for nil:NilClass 

我的儀表控制器是:

class DashboardController < ApplicationController 

    def index 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @posts } 
    end 
    end 

end 

儀表板視圖:

<div class="dash-well"> 
    <div class="gravatar-dashboard"> 
     <%= image_tag avatar_url(@user), :class => 'gravatar' %> 
     <h1 class="nuvo wtxt"><%= current_user.username.capitalize %></h1> 
    </div> 
</div> 

我的應用助手:

module ApplicationHelper 
    def avatar_url(user) 
     default_url = "#{root_url}images/guest.png" 
     gravatar_id = Digest::MD5.hexdigest(user.email.downcase) 
     "http://gravatar.com/avatar/#{gravatar_id}.png?s=200{CGI.escape(default_url)}" 
    end 

    def avatar_url_small(user) 
     default_url = "#{root_url}images/guest.png" 
     gravatar_id = Digest::MD5.hexdigest(user.email.downcase) 
     "http://gravatar.com/avatar/#{gravatar_id}.png?s=40{CGI.escape(default_url)}" 
    end 
end 

我的用戶模型:

class User < ActiveRecord::Base 

    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, 
    # :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :user_id, :id, :website, :bio, :skype, :dob, :age 

    has_many :posts 
    # attr_accessible :title, :body 
end 

我的控制面板型號:

class Dashboard < ActiveRecord::Base 
    attr_accessible :status, :author, :email, :username, :id, :user_id, :user, :website, :bio, :skype, :dob, :age 

    belongs_to :user 
end 

對不起,我是相當新的的Ruby-on-Rails的!

回答

2

試試這個:

<%= image_tag avatar_url(current_user), :class => 'gravatar' %> 
+0

BOOM!這就是CURRENT_user,這是我需要感謝的一部分。但我也需要它,以便用戶可以鍵入導航到其他用戶儀表板並查看他的gravatar,有什麼想法? – coreypizzle 2013-03-18 19:06:46

+0

你如何瀏覽..你是否提供任何鏈接給用戶? – codeit 2013-03-18 19:09:16

+0

是的,我提供了一個鏈接。 – coreypizzle 2013-03-18 19:09:40

1

你真的想這樣在你的控制器:

def index 
    @user = current_user 
    respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @posts } 
    end 
end 

注意添加第二行,其中@user變量分配給CURRENT_USER的。

然後,您在視圖中調用的@user將起作用。當您繼續使用它時,會看到一個典型的軌道模式,即以@符號開頭的大多數變量都將在該視圖的相應控制器方法中定義。因此,如果您使用帶@的變量,並且它不可用,請檢查控制器以確保它首先被定義。 (如果你想了解更多,這些被稱爲實例變量)。

爲了解決第二個問題,如果你是CURRENT_USER,你想訪問其他用戶的網頁:

def show 
    @user = User.find params[:id] 
    respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @user } 
    end 
end 

這將通過URL工作/用戶/ 1,您可以使用到同樣的呼籲avatar_url,傳遞@user,它將獲得該用戶的頭像,其中用戶是與給定用戶ID相匹配的頭像。您的控制器中可能已經有了這個確切的代碼,但希望現在您明白它爲什麼可行。

祝你好運!

相關問題