Checking Required Request Parameters

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!

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.{}) ), 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.