# Checking Required Request Parameters

**URL:** <https://www.ruby-forum.com/t/checking-required-request-parameters/143527>\
**Category:** Rails\
**Created:** [July 20, 2008, 12:08am UTC](https://www.ruby-forum.com/t/checking-required-request-parameters/143527 "2008-07-20T00:08:55Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dutone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f07891/32.png) [@dutone](https://www.ruby-forum.com/u/dutone)\
**Post date:** [July 20, 2008, 12:08am UTC](https://www.ruby-forum.com/t/checking-required-request-parameters/143527/1 "2008-07-20T00:08:55Z")

</div>

Input validation in Rails is done via ActiveRecord objects.  
Most of the time, these input values are passed directly from the  
params hash:

@bank = Bank.create(params[:bank])  
if @bank.valid?  
#do some stuff  
end

#otherwise display errors

If a required attribute was missing, that’s ok, errors are stored in  
@bank.errors and can be reported back to the user in the requested  
format (html, xml, etc…)

In another situation you might have:

@bank = Bank.find\_or\_create\_by\_name(params[:bank]  
[:name],params[:bank])  
@yeg = Yeg.find\_by\_name(params[:yeg][:name])  
@bank.robberies.create(params[:robbery]) do |r|  
r.yeg = @yeg  
end

@bank.save!

If the request has no bank parameter, you’ll get a no method error  
when accessing params[:bank][:name]. Same goes for params[:yeg].

Of course I can check the params for the desired keys, but this is  
ugly and not DRY:

@bank = Bank.create  
unless params[:bank]  
@bank.errors.some\_method\_call(“Required”)  
render :action=\>’new’  
end

#more ugly checking….

But, if the params hash –err HashWithIndifferentAccess- was auto  
vivified ( i.e. Hash.new({}) ), the above param checking wouldn’t be  
necessary. Missing fields could be communicated back in the response  
via the existing set of validation rules.

How do you all deal with this situation? I want to think that I’m  
missing something. If there was really a need for param to default,  
I’d assume that it would.
