validation of a field from another table in a specific model

Asked

Viewed 211 times

-1

It is possible to validate the field of another table that is related in a specific model?

For example, I need to validate an email field in a table Requests, but only emails from anyone who is an internal user (which is in a table Users). That is, who is an internal user must enter your email. This information comes from login (Sign-in), that is, from another table (orders belongs_to user).

In that, in the model requests, I am creating a validation def like this:

def valida_email_interno
   errors.add(:email, "Digite o email") if email.blank? and ...# a  condição que o usuario é interno, por exemplo, @pedido.user.localpedido == 1

Any idea?

1 answer

0

firstly I suggest that you create a method to check if you are an internal user (so I just wanted to check if you are associated with a user), for example:

def usuario_interno?
  user # Ou qualquer outra lógica
end

After that you can do a normal Rails validation:

validates_presence_of :email, if: :usuario_interno?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.