Validating a Ruby class, validates_inclusion_of with dynamic data

If I have an ActiveRecord model as follows

class Foo < ActiveRecord::Base validates_inclusion_of :value, :in => self.allowed_types def self.allowed_types # some code that returns an enumerable end end 

This does not work because the allow_types method was not defined at the time the validation was evaluated. All the fixes that I can think of are mainly related to moving the method definition above the check so that it is available when necessary.

I understand that this may be more a question of coding style than anything (I want all my checks to be at the top of the model and methods at the bottom), but I believe there should be some solution for this, maybe lazy model bootstrap assessment?

- is that what I want to do is even possible? Should I just define a method above validation or is there a better solution for validation in order to achieve what I want.

+6
source share
2 answers

You should use lambda syntax for this purpose. Perhaps like this:

 class Foo < ActiveRecord::Base validates_inclusion_of :value, :in => lambda { |foo| foo.allowed_types } def allowed_types # some code that returns an enumerable end end 

Thus, it will evaluate the lambda block at each check and pass the Foo instance to the block. It will then return the value from allow_types in this instance so that it can be checked dynamically.

Also note that I removed self. from the declaration of the allowed_types method, because it would create a class method instead of the instance method that you want here.

+10
source

Parameter: in the validates_inclusion_of method option, it does not seem to accept lambda or Proc. Here's a different approach:

 validates_each :product_id do |record, attrib, value| begin Product.find(value) rescue ActiveRecord::ActiveRecordError record.errors.add attrib, 'must be selected from list.' end end 
0
source

Source: https://habr.com/ru/post/895313/


All Articles