0

私は gravatar をセットアップし、それを自分のために動作させましたが、'users/*user id goes here*'. それを使用しようとするdashboard/indexたびにエラーが発生します

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 の初心者です!

4

2 に答える 2

2

これを試して:

<%= image_tag avatar_url(current_user), :class => 'gravatar' %>
于 2013-03-18T19:03:30.177 に答える
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 に割り当てる 2 行目の追加に注意してください。

次に、ビューで呼び出している @user が機能します。Rails を使い続けると現れる典型的なパターンは、@ 記号で始まるほとんどの変数が、そのビューの対応するコントローラー メソッドで定義されるということです。したがって、@ で変数を使用していて、それが使用できない場合は、コントローラーをチェックして、最初に定義されていることを確認してください。(参考までに、詳細を知りたい場合は、これらはインスタンス変数と呼ばれます)。

2 番目の問題に対処するには、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

これは /users/1 のような URL で機能します。同じ呼び出しを avatar_url に使用し、@user を渡すと、そのユーザーのアバターが取得されます。ユーザーは、指定されたユーザー ID に一致するユーザーです。おそらく、コントローラーにはこの正確なコードが既にあると思いますが、うまくいけば、なぜそれが機能するのかがわかります。

幸運を!

于 2013-06-24T21:42:35.857 に答える