d08z
d08z

Reputation: 73

Ruby on Rails: validate the presence and existence of an association

I would like to know if there is a way in rails to validate the presence (AND existence in the database) of an association without using any additional gem if possible (i.e the associated "belongs_to" object is in the database and valid before saving).

validates_presence_of does not work because you can use a newly created and unsaved object.

I know all about the validates_existence gem but I would like to avoid it if possible.

Upvotes: 2

Views: 410

Answers (1)

Petr Gazarov
Petr Gazarov

Reputation: 3821

You can use validates_associated in conjunction with validates_presence_of.

validates_associated will run validations on the associated model (which you have to define in that model).

validates_presence_of validates presence of the association.

EDIT

Addressing your comment: not a common scenario to validate presence in db specifically, but you can do this:

validate :association_exists

def association_exists
  # query database for the association record and return true if it exists
  # self is model instance inside this method
end

Upvotes: 1

Related Questions