# Add validation error from associated model to parent

**URL:** <https://www.ruby-forum.com/t/add-validation-error-from-associated-model-to-parent/141584>\
**Category:** Rails\
**Created:** [June 27, 2008, 10:42am UTC](https://www.ruby-forum.com/t/add-validation-error-from-associated-model-to-parent/141584 "2008-06-27T10:42:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![miv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/258eb7/32.png) [@miv](https://www.ruby-forum.com/u/miv)\
**Post date:** [June 27, 2008, 10:42am UTC](https://www.ruby-forum.com/t/add-validation-error-from-associated-model-to-parent/141584/1 "2008-06-27T10:42:54Z")

</div>

so basically i has this setup (example):

class FellowUser \< ActiveRecord::Base  
belongs\_to :fellow  
belongs\_to :user  
end

class Fellows \< ActiveRecord::Base  
belongs\_to :user  
has\_many :fellow\_users  
has\_many :fellows, :through =\> :fellow\_users  
end

what i want, in rspec terms, is this:

# 

# i want validation to fire if i associate user twice to fellow

# 

it “should not be able to be fellow twice” do  
@fellow.fellows \<\< users(:george)  
@fellow.fellows \<\< users(:quentin)  
@ft.fellows.size.should == 2

```
# same user second time
@fellow.fellows << users(:george)

# tried @fellow.should_not be_valid - not working either
@fellow.should have(1).error_on(:fellows)

@fellow.fellows.size.should == 2

```

end

in join model:

i tried this with no luck:  
validates\_uniqueness\_of :fellow\_id, :scope =\> :user\_id

i tried this with same result:  
validate do |record|  
# add\_to\_base, can be add(:fellows, --//–) and no luck here  
record.errors.add\_to\_base(“duplicating hitcher”) if  
record.fellow.fellows.size!=record.fellow.fellows.uniq.size  
end

in parent model:

```
this makes model not valid but it still saves and record is add to

```

join model

```
   validate do |record|
     record.errors.add(:fellows, "you can't be fellow twice") if

```

record.fellows.size!=record.fellows.uniq.size  
end

Any suggestions will be greatly appreciated.
