# Model Validation for Polymorphic association

**URL:** <https://www.ruby-forum.com/t/model-validation-for-polymorphic-association/138374>\
**Category:** Rails\
**Created:** [May 22, 2008, 12:10pm UTC](https://www.ruby-forum.com/t/model-validation-for-polymorphic-association/138374 "2008-05-22T12:10:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![selva](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/13edae/32.png) [@selva](https://www.ruby-forum.com/u/selva)\
**Post date:** [May 22, 2008, 12:10pm UTC](https://www.ruby-forum.com/t/model-validation-for-polymorphic-association/138374/1 "2008-05-22T12:10:59Z")

</div>

Hi All,

Anybody did the model validation for polymorphic association table??

class Request \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :user\_request,:polymorphic=\>true  
belongs\_to :service  
end

class WaterBill \< ActiveRecord::Base  
has\_one :request,:as=\>:user\_request,:dependent=\>:destroy

validates\_presence\_of(:name\_of\_legalperson, :message =\> “Should not be  
blank”)

end

Here validation in WaterBill model is not working…

my controller code…

def save  
@requests=Request.new()  
@requests.user\_request=WaterBill.new(params[:water\_bill])  
if @requests.save  
flash[:notice] = ‘Water Bill Was Successfully Created.’  
redirect\_to :action =\> ‘newwaterbill’  
else  
render :action =\> ‘newwaterbill’  
end  
end

Any thing wrong in this code … please clarify my doubts…

---

<div class="post-metadata">

**Author:** ![selva](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/13edae/32.png) [@selva](https://www.ruby-forum.com/u/selva)\
**Post date:** [May 22, 2008, 8:08pm UTC](https://www.ruby-forum.com/t/model-validation-for-polymorphic-association/138374/2 "2008-05-22T20:08:28Z")

</div>

On 5/22/08, Selvaraj S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> @requests=Request.new()
> @requests.user_request=WaterBill.new(params[:water_bill])
> if @requests.save
> flash[:notice] = 'Water Bill Was Successfully Created.'
> redirect_to :action => 'newwaterbill'
> else
> render :action => 'newwaterbill'
> end
> 
> ```
> 
> end
> 
> Any thing wrong in this code … please clarify my doubts…

If you use the debugger you can easily see what the model’s error hash  
contains.

script/server --debugger

Then add ‘debug’ near where the code is causing a problem.

Try changing your code so you can actually get at the errors:

@request.save  
if @request.new\_record?  
debug  
end

Also, I would choose a model name other than Request, seems too easily  
confused request.post and friends.

–  
Greg D.  
[http://destiney.com/](http://destiney.com/)
