Alex Fedoseev
Alex Fedoseev

Reputation: 1215

Rails: validates_presence_of attribute only if another attribute have specified value

I have 2 models:

  1. type — model with data types
  2. data — model with data

Model type:

Model data:

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

Answers (3)

Alex Fedoseev
Alex Fedoseev

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

nickcen
nickcen

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

Mehul Gurjar
Mehul Gurjar

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

Related Questions