Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 Rails:使用before#u操作作为';或';条件_Ruby On Rails 4_Controller - Fatal编程技术网

Ruby on rails 4 Rails:使用before#u操作作为';或';条件

Ruby on rails 4 Rails:使用before#u操作作为';或';条件,ruby-on-rails-4,controller,Ruby On Rails 4,Controller,在这种情况下,用户可以满足四个非重叠条件:A、B、C和/或D 在#show之前,除非用户满足条件A、B或C,否则应重定向用户 在#编辑、#更新和#销毁之前,应重定向用户,除非他们满足条件B或C 在#index之前,除非用户满足条件C,否则应重定向用户 在这些条件下,对于userscocontroller,是否有比下面的代码更简单、更有效或更可靠的Rails-y方法来编写before\u actions before_action :a_through_c, only: [:show] bef

在这种情况下,用户可以满足四个非重叠条件:A、B、C和/或D

  • #show
    之前,除非用户满足条件A、B或C,否则应重定向用户

  • #编辑
    #更新
    #销毁
    之前,应重定向用户,除非他们满足条件B或C

  • #index
    之前,除非用户满足条件C,否则应重定向用户

在这些条件下,对于
userscocontroller
,是否有比下面的代码更简单、更有效或更可靠的Rails-y方法来编写
before\u action
s

before_action :a_through_c, only: [:show]
before_action :b_through_c, only: [:edit, :update, :destroy]
before_action :c,           only: [:index]
...

private

def a_through_c
  b_through_c unless current_user.satisfies_condition?(a)
end

def b_through_c
  c unless current_user.satisfies_condition?(b)
end

def c
  redirect_to(root_url) unless current_user.satisfies_condition?(c)
end
正如你所知,我不是在寻找下面的代码——只有B或C才允许
\edit
\update
\destroy
通过,只有C才允许
\index
通过。下面的代码允许A、B或C通过任何操作

before_action :accessible, only: [:show, :index, :edit, :update, :destroy]
...
private

def accessible
  unless
    current_user.satisfies_condition?(a) ||
    current_user.satisfies_condition?(b) ||
    current_user.satisfies_condition?(c)
    redirect_to(root_url)
  end
end
佩尔的评论。我喜欢这个解决方案,因为它的透明度。如果这不是一个假设的例子,我肯定会重新编写
满足条件
方法来获取参数数组(用于干燥)

before_action :a_or_b_or_c, only: [:show]
before_action :b_or_c, only: [:edit, :update, :destroy]
before_action :c, only: [:index]

...

private

def a_or_b_or_c
  unless
    current_user.satisfies_condition?(a) ||
    current_user.satisfies_condition?(b) ||
    current_user.satisfies_condition?(c)
    redirect_to root_url
  end
end

def b_or_c
  unless
    current_user.satisfies_condition?(b) ||
    current_user.satisfies_condition?(c) ||
    redirect_to root_url
  end
end

def c
  unless
    current_user.satisfies_condition?(c)
    redirect_to root_url
  end
end

我将为A、B和C定义单独的方法,然后为每个所需的组合执行操作。我不确定它是否是最有铁路的,但它应该是透明的,并且易于维护。