diff --git a/README.md b/README.md index 1dd6023..395754c 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,12 @@ Thanks to Nick Kallen for the permit idea! ## Require Multiple Parameters +If you want to make sure only certain parameters have to be required you can do: + +``` ruby +params.require([:foo, :bar]) +``` + If you want to make sure that multiple keys are present in a params hash, you can call the method twice: ``` ruby diff --git a/lib/action_controller/parameters.rb b/lib/action_controller/parameters.rb index 8f43723..28f4ce6 100644 --- a/lib/action_controller/parameters.rb +++ b/lib/action_controller/parameters.rb @@ -54,8 +54,15 @@ def permit! self end - def require(key) - self[key].presence || raise(ActionController::ParameterMissing.new(key)) + def require(filter) + case filter + when Symbol, String + require_presence?(filter) + when Array + filter.each do |k| + require_presence?(k) + end + end end alias :required :require @@ -113,6 +120,10 @@ def convert_value(value) private + def require_presence?(key) + self[key].presence || raise(ActionController::ParameterMissing.new(key)) + end + def convert_hashes_to_parameters(key, value, assign_if_converted=true) converted = convert_value_to_parameters(value) self[key] = converted if assign_if_converted && !converted.equal?(value) diff --git a/test/action_controller_required_params_test.rb b/test/action_controller_required_params_test.rb index 5950f93..43ee163 100644 --- a/test/action_controller_required_params_test.rb +++ b/test/action_controller_required_params_test.rb @@ -5,6 +5,11 @@ def create params.require(:book).require(:name) head :ok end + + def update + params.require([:books, :authors]) + head :ok + end end class ActionControllerRequiredParamsTest < ActionController::TestCase @@ -16,6 +21,15 @@ class ActionControllerRequiredParamsTest < ActionController::TestCase post :create, { :book => { :title => "Mjallo!" } } assert_response :bad_request + + put :update, { :books => 'foo', :authors => 'bar' } + assert_response :ok + + put :update, { :books => { :bar => 'foo' }, :authors => 'bar' } + assert_response :ok + + put :update, { :books => 'foo' } + assert_response :bad_request end test "required parameters that are present will not raise" do