StrongParametersDsl
The missing Rails controller class method that lets you declare your strong parameters.
Installation
Add this line to your application's Gemfile:
gem 'strong_parameters_dsl'
Or install it yourself as:
$ gem install strong_parameters_dsl
Usage
When Rails came out with Strong Parameters it just didn't feel Ruby enough. This gem is a simple workaround that will let you declaratively define your strong parameters as you would your filters.
class UsersController < ActionController::Base
strong_params :user do
permit :name, :email, comments_attributes: [:comment, :post_id]
end
# ... or ...
strong_params :user, permit: [:name, :email, comments_attributes: [:comment, :post_id]]
# an additional feature added is the ability to permit a key whose value is an arbitrary hash
strong_params :user, any: :data
# you can also mix and match any of the above approaches
strong_params :user, any: :data, permit: :name do
permit :more_keys, :and_stuff
end
def create
# the named param method is created based on the argument passed
# to the strong_params call
User.create user_params
# ... rest of code ...
end
end
The block passed to strong_params
is evaluated in the context of the ActionController::Parameters instance that is returned by params
.
Or more specifically by the strongified instance returned by calling params.require(:some_key)
.
There is an issue regarding allowing arbitrary hashes in some keys which was debated here. The solution wasn't very neat but it could be added as an instance method on the Parameters instance and then used as part of this DSL. Ideas welcome.
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request