# Validates\_presence\_of , unless

**URL:** <https://www.ruby-forum.com/t/validates-presence-of-unless/136191>\
**Category:** Rails\
**Created:** [April 29, 2008, 6:25pm UTC](https://www.ruby-forum.com/t/validates-presence-of-unless/136191 "2008-04-29T18:25:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dmorin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f0a364/32.png) [@dmorin](https://www.ruby-forum.com/u/dmorin)\
**Post date:** [April 29, 2008, 6:25pm UTC](https://www.ruby-forum.com/t/validates-presence-of-unless/136191/1 "2008-04-29T18:25:19Z")

</div>

I’ve got a case for my model where the name field is required, ONLY if  
the comment field has been filled out. I thought I could do this like  
this:

validates\_presence\_of :name, :unless=\>@comment.nil?

but I can’t seem to get the syntax right, can somebody help me out? I’m  
not sure how the incoming data has been provided to the model, so that I  
can reference the value of what is going to be the comment field, if  
that makes sense.

---

<div class="post-metadata">

**Author:** ![dmorin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/f0a364/32.png) [@dmorin](https://www.ruby-forum.com/u/dmorin)\
**Post date:** [April 29, 2008, 6:38pm UTC](https://www.ruby-forum.com/t/validates-presence-of-unless/136191/2 "2008-04-29T18:38:39Z")

</div>

On Tue, Apr 29, 2008 at 12:25 PM, Duane M. \<  
removed\_email\_address@domain.invalid\> wrote:

> I’ve got a case for my model where the name field is required, ONLY if  
> the comment field has been filled out. I thought I could do this like  
> this:
> 
> validates\_presence\_of :name, :unless=\>@comment.nil?

If you want to put the condition inline, you have to do something like

validates\_presence\_of :name, :unless =\> Proc.new { |comment|  
comment.nil? })

Alternatively, you can specify a method to call.

validates\_presence\_of :name, :unless =\> :comment\_absent?

def comment\_absent?  
@comment.nil?  
end

Here are the docs:  
[http://www.railsbrain.com/api/edge/doc/index.html?a=M001604&name=validates\_presence\_of](http://www.railsbrain.com/api/edge/doc/index.html?a=M001604&name=validates_presence_of)

Regards,  
Craig
