2

这可能是一个非常n00b的问题,但是如果您的参数列表包含一堆不可访问的属性,即

params = {"controller"=>"api1/users", "action"=>"create"}

什么是“清理”你的参数的最佳方法,以便它们只包含可访问的属性。我目前想到的当前方法是:

User._accessible_attributes[:default].entries

这给了我一个可访问属性的列表,然后只传递这些参数:

["", "email", "password", "fb_token", "fb_id", "fb_name", "first_name", "last_name", "gender"

另一种可能的方法是:

  def clean_params #ANTIPATTERN
    params.delete(:controller)
    params.delete(:action)
  end

但这也感觉像是一种反模式......

我知道您应该执行类似 params[:user] 的操作来仅获取可访问的参数,但因为这是一个 API,所以能够仅在 url 中传递东西会很好。

谢谢!

4

2 回答 2

2

你可以这样做......这只会在你想要在控制器中的参数中感知。信用:dhh的要点

class UserController < ApplicationController
  respond_to :html

  def create
    respond_with User.create(user_params)
  end

  private
  def user_params
    params[:user].slice(:email, :first_name, :last_name)
  end

end
于 2012-06-15T04:06:41.770 回答
2

Rails 参数包装器会自动为您执行此操作。也就是说,它将在顶层接受参数并将它们分组,例如,:user为了您的方便,过滤掉用户模型无法访问的任何参数。它在内部使用accessible_attributes,类似于您所做的。使用您的 API 的人不需要对属性进行分组——rails 会在将参数交给您的控制器操作之前完成。

默认情况下,它为 JSON 请求打开,但您可以通过编辑initializers/wrap_parameters.rb. wrap_parameters或者,您可以使用控制器中的方法在每个控制器的基础上调整行为。

The rails scheme of parameter sanitizing is likely to change in 4.0, trending away from the model and toward the controller. You may want to watch development of the strong_parameters gem which could be a preview of things to come.

于 2012-06-15T04:13:51.940 回答