所以我顯然與布爾流混淆,因爲我每遇到一個問題。注意:我正在教自己編程,你是我唯一的學習希望!我試圖定義一個方法來檢查用戶是否是管理員,這樣我就可以在視圖中顯示某些對象,僅僅管理員就足夠簡單了......或者不是,由於某種原因,它不能識別出我是管理員(當我真的是,我查過了!)。有了這一切,我是一個新手,所以容易對我!如何使用布爾條件
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>
我不能確定,也許我有錯了地方的方法是什麼?我曾嘗試將其放置在我的應用程序控制器和我的用戶控制器中,但無濟於事。我肯定錯過了什麼。
編寫自己的登錄和認證體系是不容易的,所以你可能需要使用像[設計](https://github.com/plataformatec/devise)我一個罐頭解決方案如果你剛剛開始。請注意,你的'is_an_admin'方法不會返回任何東西,它只是做一個分支到空代碼塊的測試。你可能意味着將'if'條件的主體單獨留下,這意味着該方法實際上會返回評估結果。 – tadman
@tadman我看到了這一點,但如果我現在努力奮鬥,那麼我會輕鬆走上這條路。我學到了很多東西,用戶確實可以登錄和退出保存的會話(這非常酷,讓我永遠但是很酷!) –
我很高興你有這麼多,但它可能是一個鬥爭正確,安全地做,並以適應外部壓力的方式進行。 Devise實際上非常簡單,更重要的是,您可以輕鬆添加對OAuth等內容的支持,以便人們可以根據需要使用Twitter,Facebook或Google進行登錄。 – tadman