如果我可以在redmine控制器中的“操作之前”之后添加“ if”

时间:2019-07-16 13:57:03

标签: ruby-on-rails

我想向我的redmine插件添加权限,并且我设置了一个方法,该方法将在三种不同情况下返回三个不同的值。不同的值表示不同的权限,但是我得到有关代码的语法错误,我不知道 不知道如何解决。

class TextpollsController < ApplicationController
  before action:  if :the_value_of_the_role_id==6
                    :only => [:index,:vote,:setting]
                  elsif :the_value_of_the_role_id==7
                    :only => [:index]
                  elsif
                    deny_access
                  end

  def index
    @textpolls = Textpoll.all
  end
  ...

#the code of the_value_of_the_role_id
def the_value_of_the_role_id
    @user = User.current
    role_id=nil
     Textmember.each do|member|
       if member.user_id==@user.id
         role_id=member.role_id
       end
     end
    return role_id
  end

1 个答案:

答案 0 :(得分:1)

这是回调源代码:https://github.com/rails/rails/blob/master/actionpack/lib/abstract_controller/callbacks.rb#LC24

您会看到onlyexcept只是ifunless语句。 因此,您可以执行以下操作:

class TextpollsController < ApplicationController
  before_action :your_method, if: :should_be_called?

  def index
    @textpolls = Textpoll.all
  end

private

  def your_method
    # You can add your code here, it will be executed only if the role_id == 6
    # and if the action is :index, :vote or :setting
    # or if the role_id is == 7 and the action is :index
  end

  def should_be_called?
    # action_name is an attribute defined in rails to get the controller’s action name
    if (params[:role_id] == 6 && %w[index vote setting].include?(action_name)) ||
       (params[:role_id] == 7 && action_name == 'index')
      true
    else
      false
    end
  end
end