2014-09-26 37 views
0

我試圖在每個視圖中顯示一條警報(我已將它放入application.html.erb),只有當用戶(current_user)未上載時才顯示任何照片呢。如何在一般視圖中獲取用戶的照片

事情是,我不知道如何把我的控制器,以檢索user.photos並檢查它是否blank

在我看來

<% if @user.photos.blank? %> 
    <div class="alert-header"> 
    <i class="icon-cog green"> </i> Todavía no has subido ningún spot 
    <button class="semi_margin_left smallbutton medium"> Sube uno </button> 
    </div> 
<% end %> 

我試圖把我的pages controller

@user = current_user 
@photos = @user.photos 

做註銷時,它會給我一個錯誤。

問題是,如果我想讓@ user.photos在所有應用程序中都可用,需要觸摸哪個控制器?該警報將顯示在整個應用程序中。

感謝

+0

'@ user.photos'和'@ user'在其整體上應該可以在任何地方使用。您在哪個視圖中提供的代碼? – sebkkom 2014-09-26 12:37:50

回答

0

添加輔助方法,應用控制器:

# application_controller.rb 
before_action :check_photos_alert 

def check_photos_alert 
    @show_photo_alert = @user && @user.photos.blank? 
end 

只要確保正在調用這個動作之前@user被設定。然後在您的視圖中,您可以檢查是否設置了@show_photo_alert標誌。

<% if @show_photo_alert %> 
    <div class="alert-header"> 
    <i class="icon-cog green"> </i> Todavía no has subido ningún spot 
    <button class="semi_margin_left smallbutton medium"> Sube uno </button> 
    </div> 
<% end %> 

有一點需要注意,雖然:ApplicationController的是大多數,如果不是所有的控制器,因此它可能是太多perfom在每次請求該檢查父類。如果出現這種情況,請將此邏輯從ApplicationController移至模塊,並將此模塊包含至您需要此檢查的每個控制器。

相關問題