Defining Rails / Shared strong parameters between two controllers

has two item_controller elements, one for api (in app / controller / api /) and one for backend (in application / controllers / backend)

Strong parameters are quite long (20 fields or something else) and tell me to develop a little. It would be impossible to maintain this list in both controllers, but since the needs are more or less the same with the create / updates actions, I would consider splitting the definition of strong parameters in a separate file that will be shared and

I tried to inherit these two supercontrollers, including only a strong parameter definition:

class SharedItemsController < ApplicationController private # not knowing all the prerequisites of this, I tried also using protected instead of private; same result def item_params .... end end end class Frontend::ItemsController < SharedItemsController ... end class Api::ItemsController < SharedItemsController ... end 

No success, I'm stuck with unpermitted options

Hope to get some tips on this here at SO; it is better

+5
source share
2 answers

thanks @SergioTulentsev; in this case, the main and preferred template will be the use of the module. For example, in lib / items_controller_params.rb:

 module ItemsControllerParams def item_params params.require(:item).permit( .. your fields here ... ) end end 

Then it can be included in the respective controllers, as shown below:

  class Api::ItemsController < ApplicationController include ItemsControllerParams ... end 
+5
source

I really do not understand why you do not bet

 private def item_params params.require(:item).permit(your_fields_name) end 

in particular the controller?

if you think that you have 20-30 fields, and it will be difficult for you to add all the fields there, and that if in the future I will need to use nested attributes, then it will be even more difficult. So short hand

 private def item_params params.require(:item).permit! end 

Allow with! and that you no longer need to define each column in the parameters, even if it is nested. Good luck.

-1
source

All Articles