【问题标题】:Multipled conditions for showing and hidding buttons显示和隐藏按钮的多种条件
【发布时间】:2016-05-02 07:40:58
【问题描述】:

我正在尝试制作一个“更新和删除”按钮,该按钮仅在用户创建帖子或用户或版主 AND/OR 版主时才会显示。

我目前的 posthelper 是

  def user_is_authorized_for_post?(post)
    current_user && (current_user == post.user || current_user.admin?) 
  end

我的按钮是:

<% if user_is_authorized_for_post?(@post) %>
<%= link_to "Edit", edit_topic_post_path(@post.topic, @post), class: 'btn btn-success' %>
<%= link_to "Delete Post", [@post.topic, @post], method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this post?' } %>
<% end %>

更新:我将 PostsHelper 更新为:

  def user_is_authorized_for_post?(post)
    current_user && (current_user == post.user || current_user.admin?)  || (current_user == post.user || current_user.moderator?)
  end

它有效,但我的问题是,有没有更好的编码方式,因为我觉得它太长了。

【问题讨论】:

    标签: ruby-on-rails conditional


    【解决方案1】:

    是的,有一个更短的写法。

    您可以使用保护子句来缩短方法定义:

    def user_is_authorized_for_post?(post)
      return false unless current_user # the aforementioned guard clause
      current_user == post.user || current_user.admin? || current_user.moderator?
    end
    

    【讨论】:

      【解决方案2】:

      您的代码还可以,但更好的方法是使用授权系统来实现它,pundit 是一个不错的选择,因为这里用户可以通过 Curl 手动更新帖子邮递员

      您将拥有管理不同授权逻辑的策略类:

      政策

      class PostPolicy < ApplicationPolicy
        def edit?
          update?
        end
      
        #user is equivalent to the current_user and record == post
        def update?
          user && (user == record.user || user.admin?)  || (user == record.user || user.moderator?)
      
        end
      end
      

      在视图中授权

      <% if policy(@post).edit? %>
        # the button
      <% end %>
      

      在控制器中授权

      def edit
        @post = Post.find params[:id]
        authorized @post
      end
      
      def update
        @post = Post.find params[:id]
        authorize @post
        # Rest of your code
      end
      

      【讨论】:

      • 权威人士总体上是一个不错的建议,但在这里安装一个 3rd-party gem 进行单次检查看起来有点过分了
      • 当然,但必须指出,用户可以绕过按钮检查,这是防止它的好方法。
      • 公平地说 - 我一直在使用 Pundit,它是一个很棒的工具 :)
      猜你喜欢
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多