ParamsFor
Use service objects and the power of ActiveModel::Validations
to easy validate params in controller.
Installation
Add this line to your application's Gemfile
:
gem 'params_for'
And then execute:
$ bundle
Or install it yourself as:
$ gem install params_for
Usage
In your controller:
# app/controllers/fancy_controller.rb
class FancyController < ApplicationController
include ParamsFor::Connectors::Glue
params_for :fancy, only: [:create]
# Creates a Fancy object by checking and validating params
# before that
#
def create
...
@fancy = Fancy.new(fancy_params)
...
end
end
Or you can play with it yourself
# app/controllers/fancy_controller.rb
class FancyController < ApplicationController
include ParamsFor::Connectors::Glue
# Creates a Fancy object by checking and validating params
# before that
#
def create
...
@fancy = Fancy.new(fancy_params)
...
end
protected
# Strong params delegated to ParamsFor::Fancy
# and memoized in @fancy_params var returned by this method
#
# @return [HashwithIndifferentAccess]
def fancy_params
params_for :fancy
end
end
Some place in your application ( suggested app/validators/params_for/
)
# app/validators/params_for/fancy.rb
class ParamsFor::Fancy < ParamsFor::Base
attr_accessor :user_id, :fancy_name, :fancy_description
validates :user_id, :fancy_name, presence: true
validates :user_id, integer: true
end
Contributing
- Fork it ( https://github.com/[my-github-username]/params_for/fork )
- 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 a new Pull Request