Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails / Shared strong parameters' definition between two controllers

having two items_controller, one for the api (in app/controllers/api/) and one for the backend (in app/controllers/backend)

The strong parameters are quite long (20 fields or something) and prompt to evolve a bit. That would not be impossible to maintain this list in both controllers, but as the needs are more or less the same on the create/updates actions, I'd be looking into sharing the strong parameters definition in a separate file that would be shared to both

I've tried to inherit those two with a super controller including only the 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 parameters

Hope to get some tips on this one here on SO; best

like image 984
Ben Avatar asked Jun 11 '16 11:06

Ben


1 Answers

thanks to @SergioTulentsev; in this case a basic and preferable pattern would be to use a 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 could be included in the concerned controllers like below :

  class Api::ItemsController < ApplicationController
    include ItemsControllerParams
    ...
  end
like image 84
Ben Avatar answered Oct 16 '22 02:10

Ben