3

I want to mass update attributes of an entity.

How can I sanitize properly the params which is coming from grape?

This is my console log about the parameters:

params.except(:route_info, :token, :id)
=> {"display_number"=>"7"}
[18] pry(#<Grape::Endpoint>)> params.permit(:display_number)
ArgumentError: wrong number of arguments (2 for 0..1)
from /Users/boti/.rvm/gems/ruby-2.0.0-p353@thelocker/gems/hashie-2.0.5/lib/hashie/mash.rb:207:in `default'
[19] pry(#<Grape::Endpoint>)> params.sanitize
=> nil
Boti
  • 3,275
  • 1
  • 29
  • 54

1 Answers1

10

In grape you need to declare your params before the actual method.

Within the method the params object is a Hashie::Mash instance, and does not have APIs like permit and sanitize...

Here is the relevant documentation for declaring and validating parameters in grape:

You can define validations and coercion options for your parameters using a params block.

params do
  requires :id, type: Integer
  optional :text, type: String, regexp: /^[a-z]+$/
  group :media do
    requires :url
  end
  optional :audio do
    requires :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3
  end
  mutually_exclusive :media, :audio
end
put ':id' do
  # params[:id] is an Integer
end

When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.

If you still want to use strong parameters, you'll need to use the strong_parameters gem, and create a new instance of ActionController::Paramter yourself:

raw_parameters = { :email => "john@example.com", :name => "John", :admin => true }
parameters = ActionController::Parameters.new(raw_parameters)
user = User.create(parameters.permit(:name, :email))
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
  • Thank Uri Agassi, I knew these... I am using it across the app. This also means that I can't bulk update entity attributes... Did I understand correctly? – Boti May 30 '14 at 15:11
  • See my update regarding using strong parameters outside of a rails controller – Uri Agassi May 30 '14 at 15:23
  • Thanks this is the way I wanted :) – Boti May 31 '14 at 14:07
  • Thanks @UriAgassi! I was wondering, does params block only apply to the next GET/POST/PUT/DELETE method, or does it then require params for all GET/POST/PUT/DELETE methods in the class? Additionally, if params are nested in request body (i.e. I access them through `params[:something][:property]`), how would I declare them as required? (syntax question) – Ruben Martinez Jr. Jun 09 '14 at 17:56