Ruby on rails 如何清理Ruby/Rails中的用户权限代码?

Ruby on rails 如何清理Ruby/Rails中的用户权限代码?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在编写一个系统,每个用户都可以管理其他用户的权限 我有一个业务要求,即登录用户不能降级排名高于他们的人。我的立场如下: STAFF < MANAGER < ORGANIZATION_ADMIN 我试图为用户显示权限按钮,并使用以下丑陋的方法完成任务,但感觉像是糟糕的代码 # Iterate through all users and allow for their permissions to be modified other_users.each do |other_use

我正在编写一个系统,每个用户都可以管理其他用户的权限

我有一个业务要求,即登录用户不能降级排名高于他们的人。我的立场如下:

STAFF < MANAGER < ORGANIZATION_ADMIN
我试图为用户显示权限按钮,并使用以下丑陋的方法完成任务,但感觉像是糟糕的代码

# Iterate through all users and allow for their permissions to be modified
other_users.each do |other_user|
  buttons_to_show = get_buttons_to_show(logged_in_user, other_user)

  if buttons_to_show.include?(ORGANIZATION_ADMIN)
    puts "Make other_user #{ORGANIZATION_ADMIN}" # Will be a button on UI

  if buttons_to_show.include?(MANAGER)
    puts "Make other_user #{MANAGER}" # Will be a button on UI

  if buttons_to_show.include?(STAFF)
    puts "Make other_user #{STAFF}" # Will be a button on UI
end


def get_buttons_to_show(current_user, other_user)
  buttons_to_show = []

  if (current_user.at_least_staff? && other_user.role != MANAGER && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << STAFF
  end

  if (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << MANAGER
  end

  if current_user.at_least_organization_admin?
    buttons_to_show << ORGANIZATION_ADMIN
  end

  buttons_to_show
end                

你有没有考虑过使用类似的东西

我最近使用了它,您最终向模型添加了一些代码,如下所示:

if user.has_role? :uam_officer
  can :create, Segment
  cannot :approve, User
  cannot :reject, User
end
然后在视图中,例如:

<% if can?(:create, Segment) %>
   <%= link_to 'New', new_management_segment_path, { :class=>"btn btn-primary" } %>
<% end %>

它有助于将授权逻辑整齐地打包

我决定使用Pundit,并将所有这些方法纳入我的政策中。工作起来很有魅力,而且更干净。

在Rails代码中看到puts是很奇怪的,因为它的输出通常是无处可去的。puts就是一个例子。实际上,我的UI显示按钮就在那里,别忘了Rails.logger.debug。。。当使用Rails代码时。