K
K
Kirill Kazakov2015-10-27 15:05:55
Ruby on Rails
Kirill Kazakov, 2015-10-27 15:05:55

Validation in Rails, how to query an adjacent field?

I carry out validation in the model of the entered data:


#app/models/validate.rb
validates :email, :presence=> true,
:format=> VALID_EMAIL_REGEX,
:uniqueness=> true

I can't figure out how to add. a query to the database in the same table in the adjacent field, but which is not involved in the form set (here, the results of entering the form params[:subscribtion]) are passed to the model) ) ?
Task: check the email for uniqueness (which is done above), and also check that in the neighboring subscribe field - the value is true .
subscribe does not participate in input.
I'm spinning around has_one, but I can't figure out how to use .
I also need to apparently use the union of validation conditions, but with this later, I still can’t figure out how to make a request to the adjacent field.
UPD:
Now the request is
SELECT 1 FROM `subscriptions` WHERE (`subscriptions`.`email` = BINARY '[email protected]') LIMIT 1

but you must
SELECT 1 FROM `subscriptions` WHERE (`subscriptions`.`email` = BINARY '[email protected]') AND (`subscriptions`.'subscribe' = '1') LIMIT 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Pyankov, 2015-10-29
@ibub1ik

I don't quite understand what you want to do. But to get the required request, do this:
So the validation will only run if the subscribe field is set to true. If you also need to check that subscribe is always true, then there is this option:
I don’t really like it. It is better to think about a custom validator or validation method .

O
Orky, 2015-11-13
@Orky

"and you need to
SELECT 1 FROM `subscriptions` WHERE (`subscriptions`.`email` = BINARY '[email protected]') AND (`subscriptions`.'subscribe' = '1') LIMIT 1" - the request is invalid, because that there can be two soaps in the database, one with the subscription turned on, one with the subscription turned off.
And about validation, I agree with ibub1ik - it's better to make it a separate class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question