适用于不同控制器方法的强大参数

时间:2018-11-16 22:47:41

标签: ruby-on-rails strong-parameters

我正在Rails中创建一个控制器,我正在寻找方法为不同的控制器方法使用不同的强参数

在更新和新操作中,我想要求post

params.require(:post).permit(:body, :is_public, :title, :id)

但是在post/index中,我不需要这些参数。

如何为不同的控制器方法设置不同的要求强参数?

2 个答案:

答案 0 :(得分:6)

您的“强参数方法”只是Ruby方法。您可以有任意多个。

class PostsController < ApplicationController

  def create
    @post = Post.new(post_params)
  end

  def update
    @post = Post.find(params[:id])
    if @post.update(update_params)
      # ...
    else 
      # ...
    end
  end

  private

  def base_params
    params.require(:post)
  end

  # Don't take IDs from the user for assignment!
  def update_params
    base_params.permit(:body, :title)
  end

  def create_params
    base_params.permit(:body, :title, :foo, :bar)
  end
end

您也可以根据需要命名。称其为[resource_name]_params只是一种脚手架惯例。

但是强大的参数只是将参数列入白名单以避免大量分配漏洞的一种机制。它们并没有神奇地清除参数(仅允许使用某些标量类型)。

在99.9%的情况下,您将只处理更新中具有强参数的参数,并创建与POST和PUT / PATCH对应的操作。这些是从用户获取参数哈希并将其传递给模型的操作。如果您不小心将许可参数列入白名单,则可能会存在潜在的批量分配漏洞。

showeditdestroy操作通常仅采用ID形式的单个参数。 new很少使用任何参数,而index仅在构建某种搜索或过滤条件时才使用参数。

showeditnewindex是GET路由,因此它们应是幂等的,不得更改或创建资源。

除非您真的完全弄乱了所有内容,否则这些都没有任何真正的潜在潜在大规模分配漏洞。

答案 1 :(得分:2)

只需做

class FooController < ApplicationController


  def create
    @post = Post.new(create_params)
    if @post.save
      blah
    else
      blah
    end
  end

  def index
    ... something else
  end

private

  def create_params 
    params.require(:post).permit(:body, :is_public, :title, :id)
  end

end
相关问题