L
L
Lesha Fedoseev2014-01-06 18:05:13
Ruby on Rails
Lesha Fedoseev, 2014-01-06 18:05:13

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:

  1. type - reference model with data types
  2. data - model with data

Model type :
  • id- key
  • name- type name

data model :
  • id- key
  • type_id— data type id
  • main_value- required data
  • opt_value- optional data (mandatory only for a certain type)

How to properly set up the presence validation opt_value, provided that I know for sure that a certain type.nameone exists and does not change?
I have tried something like:
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

But it doesn't work.
Of course, I insert data types into the directory during migration and I know which id gets the type I need, but hardcoding id in the check ( :if => lambda { self.type_id == 2 }) just went in my opinion.
How to write such checks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexesDev, 2014-01-06
@alexfedoseev

Is not it?

def get_type_id
  Type.find_by!(name: 'i_know_this_type_exists').id
  #                                              ^^^
end

You are comparing an object with a number. find_by! will throw an exception if it doesn't find anything by name... it's more appropriate to use a similar method here.
And it's better to do that...
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 question

Ask a Question

731 491 924 answers to any question