Answer the question
In order to leave comments, you need to log in
How to check for the presence of a parameter value (validates_presence_of) provided that the second parameter has a certain value?
This is the second time I've run into the following question while writing a presence validation.
I have 2 models:
id
- keyname
- type nameid
- keytype_id
— data type idmain_value
- required dataopt_value
- optional data (mandatory only for a certain type)opt_value
, provided that I know for sure that a certain type.name
one exists and does not change? validates_presence_of :opt_value, :if => lambda { self.type_id == get_type_id }
def get_type_id
Type.find_by(name: 'i_know_this_type_exists') # с и без .id
end
:if => lambda { self.type_id == 2 }
) just went in my opinion. Answer the question
In order to leave comments, you need to log in
Is not it?
def get_type_id
Type.find_by!(name: 'i_know_this_type_exists').id
# ^^^
end
validates_presence_of :opt_value, if: :have_opt_value?
def have_opt_value?
type_id == ::Type.find_by!(name: 'super').id
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question