【问题标题】:Using rails before_action if it is only executed in certain cases如果仅在某些情况下执行,则使用 rails before_action
【发布时间】:2021-04-29 07:05:46
【问题描述】:

以下是我为我的 Rails 显示审查应用程序编写的控制器之一的代码。请注意,我没有将 Devise 用于用户身份验证。 我现在面临的问题是我希望用户(pco)只有在他/她是最初上传节目的人时才能更新节目。在这里,authorized_as_pco_to_show 可以确定,但它需要将@show 作为参数传递给它。因此,我不能使用before_action

我现在的方法是将这个authorized_as_pco_to_show 方法放在每个操作的开头,只允许正确的 pco 访问它。我想知道是否有更好的方法来做到这一点。任何帮助将不胜感激!

  def update
    authorized_as_pco_to_show @show
    
    respond_to do |format|
      if @show.update(show_params)
        format.html { redirect_to @show, notice: "Show was successfully updated." }
        format.json { render :show, status: :ok, location: @show }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @show.errors, status: :unprocessable_entity }
      end
    end
  end

【问题讨论】:

  • @show 来自哪里?如果在填充后将其插入,则可以在 before_action 中使用它。一切都是为了订购。

标签: ruby-on-rails ruby devise


【解决方案1】:

如果需要,您可以将参数传递给之前的操作。而不是这个:

before_action :authorized_as_pco_to_show

你可以使用:

before_action do
  authorized_as_pco_to_show @show
end

但是,正如 cmets 中所述,您需要从某个地方获得该节目。假设你有另一个 before_action 沿着load_show 的行将它加载到一个实例变量中,那么你可以在你的另一个 before_action 中使用它。像这样的:

before_action :load_show, :authorized_as_pco_to_show

# your actions here

private

def load_show
  @show = Show.find(params[:id])
end

def authorized_as_pco_to_show
  @show.authorized? # replace with whatever your checks are
end

【讨论】:

    猜你喜欢
    • 2013-05-21
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多