Forum: Ruby on Rails Validates

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.
Ead43bcb0202410540a6a7cee5955d46?d=identicon&s=25 Fresh Mix (giga)
on 2009-02-24 09:56
If I have a table: users(id, name, address, city)

How can I validate:
Name must be entered, but address and city can be null, but if there is
address, there also must be a city. So city can't be null, if address is
not, but bouth address and city can be null.


validates_presence_of name
validates ????
0348be81e22f24afdaa6e4f137aa9dfc?d=identicon&s=25 Priya Buvan (priyadharsini)
on 2009-02-24 10:11
Jo Jo wrote:
> If I have a table: users(id, name, address, city)
>
> How can I validate:
> Name must be entered, but address and city can be null, but if there is
> address, there also must be a city. So city can't be null, if address is
> not, but bouth address and city can be null.
>
>
> validates_presence_of name
> validates ????


Hi,
    Try with following code.

def validate
   errors.add(:city,"City should not be empty") if city==nil and
address!=nil
end
A91bd6cef23eb3516245a092e196c4da?d=identicon&s=25 Maurício Linhares (mauricio)
on 2009-02-24 17:56
(Received via mailing list)
class User
  validates_presence_of :name
  validates_presence_of :city, :if => :address
  validates_presence_of :address, :if => :city
end

-
Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)
This topic is locked and can not be replied to.