Forum: Ruby on Rails Validate two fields so they do not match

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ryan P. (Guest)
on 2006-02-28 09:44
(Received via mailing list)
Hey all,

I have two form fields (select dropdowns) that are 'startlocation' and
'endlocation'. These two cannot be equal to each other on save and I am
wondering how to put validation into the model for this. Is is possible
to
do it in the model, or do I need to do this in the controller?

Thanks in advance!

Ryan
Matt B. (Guest)
on 2006-02-28 14:33
Ryan P. wrote:
> Hey all,
>
> I have two form fields (select dropdowns) that are 'startlocation' and
> 'endlocation'. These two cannot be equal to each other on save and I am
> wondering how to put validation into the model for this. Is is possible
> to
> do it in the model, or do I need to do this in the controller?
>
> Thanks in advance!
>
> Ryan

You can do it by overriding the validate method on the model e.g.

def validate
  errors.add('startlocation', 'must be different to endlocation') if
startlocation == endlocation
end

which will get called on every save. You can also override
validate_on_create and validate_on_update to get finer grained control.

Matt
This topic is locked and can not be replied to.