Reputation: 1215
I have 2 models:
Model type:
id
— keyname
— type nameModel data:
id
— key type_id
— id of data typemain_value
— required dataopt_value
— optional data (it required only for specified data type)How can I validates_presence_of
opt_value
, if I know that specified type.name
exists and can't be changed?
I tried this method:
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') # with and without .id
end
But it doesn't work. I think because I don't have access from Data
model to Type
model.
Though I may insert predefined data types within migration and know which id
have specified data type, but I don't want to hardcode this id
within validation :if => lambda { self.type_id == 2 }
(even if it works).
How can I validate such cases?
Upvotes: 0
Views: 117
Reputation: 1215
I've got this suggestion from user alexesDev on another site. It works.
validates_presence_of :opt_value, if: :have_opt_value?
def have_opt_value?
type_id == Type.select('id').where(name: 'some type').first
end
Upvotes: 0
Reputation: 1692
I think the special type logic should be resident in the Type class
class Type < ActiveRecord::Base
def self.special_type
Type.find_by(name: 'i_know_this_type_exists').id
end
end
Use Proc instead of lambda
class Model < ActiveRecord::Base
validates_presence_of :opt_value, :if => Proc.new{|f| f.type_id == Type.special_type }
end
Upvotes: 0
Reputation: 284
You can try this
validates :opt_value, :presence => true, :if => Proc.new {|optvalue| optvalue.is_verified? }
def is_verified?
self.is_verified == "Verified"
end
Upvotes: 1