2017-04-26 42 views
0

所以我顯然與布爾流混淆,因爲我每遇到一個問題。注意:我正在教自己編程,你是我唯一的學習希望!我試圖定義一個方法來檢查用戶是否是管理員,這樣我就可以在視圖中顯示某些對象,僅僅管理員就足夠簡單了......或者不是,由於某種原因,它不能識別出我是管理員(當我真的是,我查過了!)。有了這一切,我是一個新手,所以容易對我!如何使用布爾條件

helpers/sessions_helper被兩個我的用戶和博客帖子型號:

def current_user #determines if user is logged out or is the current user of the session/cookie of profile 
    if (user_id = session[:user_id]) 
    @current_user ||= User.find_by(id: user_id) 
    elsif (user_id = cookies.signed[:user_id]) 
    user = User.find_by(id: user_id) 
    if user && user.authenticated?(cookies[:remember_token]) 
     log_in user 
     @current_user = user 
    end 
    end 
end 

def current_user?(user) 
    user == current_user 
end 

def is_an_admin 
    if current_user && current_user.admin? 
    end 
end 

<div class="col-xs-12"> 
    <h1><%= @blogpost.title %></h1> 
    <p><%= @blogpost.content %></p> 
    <% if is_an_admin %> 
    <%= link_to "Return to blog", blogposts_path %> 
    <%= link_to "Edit Post", edit_blogpost_path, class: 'btn btn-primary' %> | 
    <%= link_to "Delete Post", blogpost_path(@blogpost), 
       method: :delete, data: {confirm: "Are you sure?"}, class: 'btn btn-danger' %>  
    <% else %> 
    <%= link_to "Return to blog", blogposts_path %> 
    <% end %> 
</div> 

我不能確定,也許我有錯了地方的方法是什麼?我曾嘗試將其放置在我的應用程序控制器和我的用戶控制器中,但無濟於事。我肯定錯過了什麼。

+0

編寫自己的登錄和認證體系是不容易的,所以你可能需要使用像[設計](https://github.com/plataformatec/devise)我一個罐頭解決方案如果你剛剛開始。請注意,你的'is_an_admin'方法不會返回任何東西,它只是做一個分支到空代碼塊的測試。你可能意味着將'if'條件的主體單獨留下,這意味着該方法實際上會返回評估結果。 – tadman

+0

@tadman我看到了這一點,但如果我現在努力奮鬥,那麼我會輕鬆走上這條路。我學到了很多東西,用戶確實可以登錄和退出保存的會話(這非常酷,讓我永遠但是很酷!) –

+0

我很高興你有這麼多,但它可能是一個鬥爭正確,安全地做,並以適應外部壓力的方式進行。 Devise實際上非常簡單,更重要的是,您可以輕鬆添加對OAuth等內容的支持,以便人們可以根據需要使用Twitter,Facebook或Google進行登錄。 – tadman

回答

1

你sintax弄亂,但我認爲你總是在is_an_admin方法返回nil:

def is_an_admin 
    if current_user && current_user.admin? 
    end 
end 

它做什麼,如果因此它總是返回nil

更改它的條件爲真喜歡的東西:

def is_an_admin? 
    current_user and current_user.admin? # or shorter: current_user.try('admin?') 
end 
+2

在Ruby 2.4+中,您還可以使用'current_user&.admin?'來使用安全導航操作符。 – tadman

+0

好吧,那麼如何和VS &&有什麼不同?我也嘗試過閱讀並在我的觀點中使用它,直到我決定當我可以簡單地製作一種方法時不斷重寫,這太笨拙了。看起來我很接近,但傷心地接近不夠好。 @tadman什麼是安全導航器? –

+0

@ColtonVanBastelaere在這種情況下,他們以相同的方式工作,所以我喜歡使用更易讀的「和」而不是「&&」,檢查stackoverflow,有差異,但它更好地解釋具體問題和谷歌http:// www。 virtuouscode.com/2010/08/02/using-and-and-or-in-ruby/ – arieljuod

相關問題