0

I have a Rails application where user parameters are all provided via a RESTful API with JSON parameters. Specifically, there is no client-side HTML form from which the user posts data: it's raw JSON.

So to create a new Car entry, the user might:

POST www.mysite.com/api/car
model=Ford&year=2012

In my app, by the time I receive this, the Action Pack values are intermingled with the user values in the params[] hash, so I get:

params = {:model=>"Ford", :year=>"2012", :format=>"json", :action=>"create", :controller=>"api/cars"}

What's the best way to separate the user-generated parameters from parameters generated by Action Pack? The best I can think of is to delete the latter:

car_params = params.reject {|k,v| [:format, :action, :controller].member?(k)}
car = car.new(car_params)

but that doesn't smell right. Is there a better way? (For example, can I get Action Pack to encapsulate the user supplied params into a single hash and pass that as a single element of params[]?)

fearless_fool
  • 33,645
  • 23
  • 135
  • 217

1 Answers1

0

Don't know if it can help, but I'd just create a method in application_controller :

def user_params
  return params.reject {|k,v| [:format, :action, :controller].member?(k)}
end

So throughout the code, you can just use user_params when you don't want ActionPack params

Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
  • Yeah, I put a function like that in my application_helper.rb file. I was hoping that there was some trick to make it so I don't need it at all! – fearless_fool Aug 07 '12 at 16:09
  • And since this is Rails: `params.exclude(:format, :action, :controller)` is way more concise. – fearless_fool Aug 07 '12 at 23:41
  • When I try your more concise `params.exclude(:format, :action, :controller)` I get "undefined method `exclude`" – samjewell Jul 13 '16 at 16:59