Last Updated: February 25, 2016
·
4.604K
· ingemar

Clean up your strong parameters in Rails 4

This is a dry way to deal with strong parameters in Ruby on Rails 4. It works excellent together with the great gem decent_exposure.

module ParamsFor
  def params_for(model, *attributes)
    return if method_defined? "#{model}_params"

    define_method "#{model}_params" do
      params.require(model).permit attributes
    end
    private "#{model}_params"
  end
end

Save the snippet as lib/params_for.rb and require the file in an initializer, as usual. Then extend your application controller and tell decent_exposure to use the strong parameter strategy.

class ApplicationController < ActionController::Base
  extend ParamsFor

  decent_configuration do
    strategy DecentExposure::StrongParametersStrategy
  end
end

In your controller you can now define what params to extract with just one tidy line.

class UsersController < ApplicationController
  expose :user, attributes: :user_params

  params_for :user, :name, :email
end

Your params hash will be available through the method #user_params, as expected.

Happy coding!