# How to validate presence of associated?

**URL:** <https://www.ruby-forum.com/t/how-to-validate-presence-of-associated/149405>\
**Category:** Rails\
**Created:** [September 24, 2008, 2:35pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-associated/149405 "2008-09-24T14:35:17Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Christian\_RishSSSSj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f1d935/32.png) [@Christian\_RishSSSSj](https://www.ruby-forum.com/u/Christian_RishSSSSj)\
**Post date:** [September 24, 2008, 2:35pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-associated/149405/1 "2008-09-24T14:35:17Z")

</div>

On Rails 2.1.1, I have this simple case:

class Post \< ActiveRecord::Base  
has\_many :comments  
end

class Comment \< ActiveRecord::Base  
belongs\_to :post  
validates\_presence\_of :post\_id  
end

Now, when building associated comments to an unsaved post, the  
validation fails:

p = Post.new  
=\> #\<Post id: nil, name: nil, created\_at: nil, updated\_at: nil\>

c = p.comments.build  
=\> #\<Comment id: nil, text: nil, comment\_id: nil, created\_at: nil,  
updated\_at: nil\>

c.valid?  
=\> false

c.errors  
=\> #\<ActiveRecord::Errors:0x23f8d18 @base=#\<Comment id: nil, text:  
nil, comment\_id: nil, created\_at: nil, updated\_at: nil\>,  
@errors={“post\_id”=\>[“can’t be blank”]}\>

According to [http://dev.rubyonrails.org/ticket/4147](http://dev.rubyonrails.org/ticket/4147),  
validates\_presence\_of the foreign key is the proper way to validate  
the presence associated objects. However, the documentation warning  
regarding this was later removed.

So, question is: How do I validate the presence of associated objects,  
while still allowing the building of associated objects to an unsaved  
model?

Regards,

Christian

---

<div class="post-metadata">

**Author:** ![Christian\_RishSSSSj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f1d935/32.png) [@Christian\_RishSSSSj](https://www.ruby-forum.com/u/Christian_RishSSSSj)\
**Post date:** [September 24, 2008, 2:55pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-associated/149405/2 "2008-09-24T14:55:54Z")

</div>

Christian Rishøj wrote:

> end
> 
> the presence associated objects. However, the documentation warning  
> regarding this was later removed.
> 
> So, question is: How do I validate the presence of associated objects,  
> while still allowing the building of associated objects to an unsaved  
> model?

Christian, this comes up quite often. I’m glad the incorrect  
warning has been removed from the API, but I would dispute the  
validity of that old ticket [the blog post explaining the  
ticket-creator’s reasoning is no longer available].

Here’s my most recent post on this topic:  
[http://groups.google.com/group/rubyonrails-talk/msg/3c01e9b320604dc8](http://groups.google.com/group/rubyonrails-talk/msg/3c01e9b320604dc8)

–  
Rails Wheels - Find Plugins, List & Sell Plugins -  
[http://railswheels.com](http://railswheels.com)

---

<div class="post-metadata">

**Author:** ![Christian\_RishSSSSj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f1d935/32.png) [@Christian\_RishSSSSj](https://www.ruby-forum.com/u/Christian_RishSSSSj)\
**Post date:** [September 24, 2008, 8:23pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-associated/149405/3 "2008-09-24T20:23:30Z")

</div>

On Sep 24, 2:52 pm, Mark J. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > So, question is: How do I validate the presence of associated objects,  
> > while still allowing the building of associated objects to an unsaved  
> > model?
> 
> Christian, this comes up quite often. I’m glad the incorrect  
> warning has been removed from the API, but I would dispute the  
> validity of that old ticket [the blog post explaining the  
> ticket-creator’s reasoning is no longer available].
> 
> Here’s my most recent post on this topic:[http://groups.google.com/group/rubyonrails-talk/msg/3c01e9b320604dc8](http://groups.google.com/group/rubyonrails-talk/msg/3c01e9b320604dc8)

Thank you for this, Mark.

I was able to make the association proxy set the target object on  
unsaved associations with the following monkey patch:

module ActiveRecord  
module Associations  
class AssociationProxy  
protected  
#  
# Allow validates\_presence\_of :target on belongs\_to  
associations  
# before the target has been saved.  
def set\_belongs\_to\_association\_for(record)  
record[“#{@reflection.options[:as]}_type"] =  
 @owner.class.base\_class.name.to\_s if @reflection.options[:as]  
if @owner.new\_record?  
set\_proxy\_target\_method = "set_#{@reflection.options[:as] ||  
@reflection.primary\_key\_name.chomp(‘\_id’)}\_target”  
record.send(set\_proxy\_target\_method, @owner)  
elsif @reflection.options[:as]  
record[“#{@reflection.options[:as]}\_id”] = @owner.id  
else  
record[@reflection.primary\_key\_name] = @owner.id  
end  
end  
end  
end  
end

Now I can do:

p = Post.new  
=\> #\<Post id: nil, name: nil, created\_at: nil, updated\_at: nil\>

c = p.comments.build  
=\> #\<Comment id: nil, text: nil, post\_id: nil, created\_at: nil,  
updated\_at: nil\>

c.valid?  
=\> true

Now I wonder: Why doesn’t ActiveRecord do this by default?

Christian

---

<div class="post-metadata">

**Author:** ![Christian\_RishSSSSj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f1d935/32.png) [@Christian\_RishSSSSj](https://www.ruby-forum.com/u/Christian_RishSSSSj)\
**Post date:** [September 25, 2008, 1:43am UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-associated/149405/4 "2008-09-25T01:43:16Z")

</div>

On Sep 24, 8:22 pm, Christian Rishøj [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> protected
> record.send(set_proxy_target_method, @owner)
> 
> ```
> 
> Now I can do:
> 
> Now I wonder: Why doesn’t ActiveRecord do this by default?

Seems I’m not the first to get this idea:  
[http://www.nabble.com/-set\_belongs\_to\_association\_for-doesn’t---td11423337.html](http://www.nabble.com/-set_belongs_to_association_for-doesn't---td11423337.html)

Problem is that setting the (unsaved) owner object on an associated  
object causes a lot of tests to break. Namely, validations go into a  
recursion of e.g. validate\_associated\_records\_for\_developer and  
validate\_associated\_records\_for\_audit\_logs back and forth ad  
infinitum.

This could really be working a lot better.

Any clues on how to deal with this?

Christian

---

<div class="post-metadata">

**Author:** ![Christian\_RishSSSSj](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/f1d935/32.png) [@Christian\_RishSSSSj](https://www.ruby-forum.com/u/Christian_RishSSSSj)\
**Post date:** [September 27, 2008, 12:55pm UTC](https://www.ruby-forum.com/t/how-to-validate-presence-of-associated/149405/5 "2008-09-27T12:55:25Z")

</div>

Christian Rishøj wrote:

> Problem is that setting the (unsaved) owner object on an associated  
> object causes a lot of tests to break. Namely, validations go into a  
> recursion of e.g. validate\_associated\_records\_for\_developer and  
> validate\_associated\_records\_for\_audit\_logs back and forth ad  
> infinitum.

I guess it’s the tests that require fixing. And AR should be  
detecting loopy validations and raising an error.

–  
Rails Wheels - Find Plugins, List & Sell Plugins -  
[http://railswheels.com](http://railswheels.com)
