Reputation: 688
I'm new to ruby on rails
. I come across ParamsWrapper
in ActionController
while studying about Parameters in Ruby. I would like to know the real usage of it ?
It would be better, If you provide link for tutorials on ParamsWrapper
.
Thanks in advance.
Upvotes: 1
Views: 599
Reputation: 3243
Being in a Rails train for a couple years, haven't seen yet any useful (or suitable) use case while dealing with forms (except searching) or views in general, to be more specific.
The real ParamsWrapper
usefullness (in my opinion) comes while dealing with an app API. Consider a case, app has /users
API accessible by third parties and one wants to get user data, e.g. by typing: {"name": "Foo"}
.
With ParamsWrapper
defined for users controller:
class UsersController < ApplicationController
wrap_parameters format: [:json, :xml]
end
or, to be more generic:
class ApplicationController
wrap_parameters format: [:json, :xml]
end
it is quite easy to filter such user, because params are wrapped into user key {"name" => "Foo", "user" => {"name" => "Foo"}}
. Now, to filter given user, one would to type simply User.where(params[:user])
(or User.find_by(params[:user])
to match particular user).
What's the advantage of such approach? You do not need to bother, which param belong to what model, they're just matched for given model attribute_names
.
Upvotes: 2
Reputation: 1702
The wrapper is supposed to ease integration with REST clients allowing the client to send a root element with the model name if they want, and allowing your application to access it without having to deal with the logic of checking if the root element is there.
It's a trivial thing, but it comes in handy when you don't have control over all clients specially for applications that are already running.
I always leave it turned on in config/initializers/wrap_parameters.rb
with
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
Upvotes: 1