2012-11-22 37 views
2

我最近開始在rails上學習ruby,並且我能夠成功創建應用程序並使用設計添加用戶,還用回形針給用戶添加了頭像。Ruby on Rails無法在應用程序中顯示回形針頭像

現在我遇到了如何在整個應用程序中顯示頭像的問題。頭像只顯示http:localhost:3000/users/...用於爲例(在色器件文件夾內),但如果我嘗試創建一個新的頁面,模式,控制器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 

謝謝!

+0

這裏絕對需要更多的上下文。乍一看,它看起來像'@ user'變量沒有在您的配置文件控制器中定義。請發佈你的'Profile'模型和控制器的代碼。 – jordanpg

+0

謝謝。我剛剛用我的模型和控制器更新了這個問題。希望這個幫助。 –

+0

你首先需要找到方法'avatar?'被調用的位置(注意這與你在樣本中顯示的方法'avatar'不同'<%= image_tag @ user.avatar.url(:thumb)% >'。 – cdesrosiers

回答

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時,它將被重定向到登錄表單。

+0

完美的工作。我最初有'@user = User.find(current_user.username)',但是我收到了一些奇怪的錯誤。 Obrigado! –

+0

不錯,所以不要忘記標記我的答案是正確的:) –

0

我對Rails還是個新手,所以如果我錯了,請糾正我,但我認爲這可能適用於您。

class UserController < ApplicationController 
    def profile 
    @user = User.find(current_user.username) 
    end 
end 
+0

不,不幸的是,這沒有奏效。 –

+0

在這種情況下,你的主鍵是什麼? – Blackninja543

+0

我已經使用了'@user = current_user',它工作正常,謝謝反正!:) –

相關問題