ParamsWrapper в рубине на рельсах?

Обновить

December 2018

Просмотры

315 раз

1

Я новичок ruby on rails. Я сталкиваюсь ParamsWrapperв ActionControllerто время как изучение о параметрах в Ruby. Я хотел бы знать реальное использование этого?

Было бы лучше, если вы предоставите ссылку на учебники по ParamsWrapper.

Заранее спасибо.

2 ответы

1

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
2

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.