Validates_presence_of , unless

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.

On Tue, Apr 29, 2008 at 12:25 PM, Duane M. <
[email protected]> 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

Regards,
Craig