# Polymorphic validation

**URL:** <https://www.ruby-forum.com/t/polymorphic-validation/107214>\
**Category:** Rails\
**Created:** [June 19, 2007, 10:22am UTC](https://www.ruby-forum.com/t/polymorphic-validation/107214 "2007-06-19T10:22:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pabloz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c37758/32.png) [@pabloz](https://www.ruby-forum.com/u/pabloz)\
**Post date:** [June 19, 2007, 10:22am UTC](https://www.ruby-forum.com/t/polymorphic-validation/107214/1 "2007-06-19T10:22:53Z")

</div>

Hello

I have 2 models.

link.rb

has\_many :categories, :as =\> :categorized  
validates\_presence\_of :name, :url, :created\_at, :category

category.rb

belongs\_to :categorized, :polymorphic =\> true  
validates\_presence\_of :name

Everything seems to work. I select my category from a select tag. The  
problem is i don’t know how to validate if category is for example  
empty  
(nothing in a select tag), i would like to display the validation  
error  
along with other validation errors for link.

My create link controller.

def create  
@link = Link.new(params[:link])

```
if @link.save
flash[:notice] = 'Link was successfully created.'
category = Category.new(params[:category][:id])
category.categorized = @link
category.save
else
render :action => "new"
end

```

end

---

<div class="post-metadata">

**Author:** ![pabloz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c37758/32.png) [@pabloz](https://www.ruby-forum.com/u/pabloz)\
**Post date:** [June 19, 2007, 11:20am UTC](https://www.ruby-forum.com/t/polymorphic-validation/107214/2 "2007-06-19T11:20:46Z")

</div>

Perhaps try enclosing the ‘save’ into a begin/rescue block?

I have something similar:

class Keyword \< ActiveRecord::Base  
has\_many :rules, :order =\> :position  
\<–\>

keywords\_controller:

def addrule  
@keyword = Keyword.find(params[:id])  
rule\_description = params[:rule][:description].strip  
# exclamation mark after create method call forces validation  
begin @keyword.rules.create!(:description =\> rule\_description)  
flash[:notice] = “New rule was successfully added.”  
rescue Exception  
flash[:notice] = "Error saving rule: " + rule\_description +  
“  
”  
flash[:notice] \<\< $!.message  
end  
redirect\_to :action =\> ‘show’, :id =\> @keyword  
end

---

<div class="post-metadata">

**Author:** ![pabloz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c37758/32.png) [@pabloz](https://www.ruby-forum.com/u/pabloz)\
**Post date:** [June 19, 2007, 6:00pm UTC](https://www.ruby-forum.com/t/polymorphic-validation/107214/3 "2007-06-19T18:00:07Z")

</div>

First of all I am sorry for triple post (accident).  
Thank you for reply. I will look into your solution.

On 19 Cze, 11:20, Isabelle P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
