2

私は最近Ruby on Railsを学び始め、アプリを作成してdeviseでユーザーを追加し、ペーパークリップでユーザーにアバターを追加することに成功しました。

今、アプリ全体でアバターを表示する方法に問題があります。アバターは、例としてhttp:localhost:3000/users/...(deviseフォルダー内に)のみ表示されますがhttp://localhost:3000/profile/、タグを使用して、例として新しいページ、モデル、コントローラーを作成しようとすると

<%= image_tag @user.avatar.url(:thumb) %>

ページが読み込まれず、このエラーが返されます

undefined method 'avatar?' for nil:NilClass

それはおそらく本当に単純なことですが、それを修正する方法がわかりません。

私のモデルuser.rbは次のようになります。

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates_uniqueness_of :username

  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }

  attr_accessible :name, :username, :email, :password, :password_confirmation, :remember_me, :avatar
  attr_accessor :current_password
end

そして、私のコントローラーは次のようになります。

class UserController < ApplicationController
  def profile
  end
end

ありがとう!

4

2 に答える 2

2

routes.rb には、次のようなものが必要です。

match "profile" => "user#profile"

では、UserController次のようなものが必要です。

class UserController < ApplicationController
  def profile
    @user = current_user
  end
end

そして、あなたは使用できるようになります @user.avatar.url。また、ログインしているユーザーがいない場合、 current_user が になりnil、説明したエラーが発生することに注意してください。コントローラーに次のようなものを追加してください。

class UserController < ApplicationController
  before_filter :authenticate_user!

  def profile
    @user = current_user
  end
end

そして、認証されていないアカウントが にアクセスしようと/profileすると、ログイン フォームにリダイレクトされます。

于 2012-11-22T17:18:03.113 に答える
0

私はまだRailsに慣れていないので、間違っている場合は修正してください。

class UserController < ApplicationController
  def profile
    @user = User.find(current_user.username)
  end
end
于 2012-11-22T03:54:23.040 に答える