Frage

this may be a really n00b question, but if your list of params contains a bunch of stuff that isn't an attribute accessible, ie

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

what is the best way to "sanitize" your params so that they only contain the accessible attributes. The current way that I thought of currently is to do :

User._accessible_attributes[:default].entries

that gives me a list of accessible attributes and then only pass those params:

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

Another possible way is to have this:

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

but this also feels like an antipattern...

I know that you're supposed to do something like params[:user] to get only the accessible params, but because this is an API, it would be nice to be able to pass things just in the url.

Thanks!

War es hilfreich?

Lösung

The Rails parameter wrapper will do this for you automatically. That is, it will accept parameters at the top level and group them under, for example, :user for your convenience, filtering out any that are not accessible to the User model. Internally it uses accessible_attributes, similar to what you've done. People who use your API will not need to group attributes -- rails will do it before it hands the params to your controller action.

By default it's turned on for JSON requests, but you can expand that by editing initializers/wrap_parameters.rb. Or you can adjust the behavior on a per-controller basis using the wrap_parameters method in your controller.

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.

Andere Tipps

You could do it this way... This will only sense in the parameters you want to in the controller. credit: dhh's gist

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top