2017-04-26 47 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

相关问题