【问题标题】:How do I get this if statement with && to work properly?如何让 && 的 if 语句正常工作?
【发布时间】:2014-11-03 14:10:01
【问题描述】:

我认为这是:

<% if user_signed_in? && current_user.has_role? :admin or :editor %>

这会返回这个错误:

syntax error, unexpected tSYMBEG, expecting keyword_then or ';' or '\n'

我也试过这个:

<% if user_signed_in? and current_user.has_role? :admin or :editor %>

虽然我没有收到上述错误,但它根本不起作用......即non-signed-in-user 可以访问该 if 块中的内容。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 devise cancancan


    【解决方案1】:

    我认为has_role? 不能接受多个参数。正确的做法是:

    <% if user_signed_in? && (current_user.has_role? :admin or current_user.has_role? :editor) %>
    

    【讨论】:

      【解决方案2】:

      我找到了更惯用的写法,即使用[has_any_role?][1]

          <% if user_signed_in? and current_user.has_any_role? :admin, :editor %>
      

      【讨论】:

        【解决方案3】:

        你可以,试试这个方法:

        <% if user_signed_in? && [:admin, :editor].include?(current_user.role) %>
        

        【讨论】:

        • 不...这不起作用。我收到以下错误:syntax error, unexpected tIDENTIFIER, expecting keyword_then or ';' or '\n'
        猜你喜欢
        • 1970-01-01
        • 2013-11-23
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 2020-07-09
        • 2019-07-23
        • 2017-11-25
        • 2016-03-04
        相关资源
        最近更新 更多