Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class methods from inclusion validation

I would like to include a class method as my options when using the inclusion validation:

class Search < ActiveRecord::Base

  attribute :foo, Array
  validates :foo, inclusion: class_method_options

  def self.class_method_options
   ['foo', 'bar']
  end
end

However I get undefined method 'class_method_options' for Search:Class (NoMethodError).

I tried Googling for the solution, but just found how to create a custom validation. I don't need a whole new validation, I just want to use the standard Rails inclusion validator. How can I access class_method_options from the inclusion validation?

like image 816
ang.gove Avatar asked Aug 21 '14 01:08

ang.gove


1 Answers

It's just not defined yet.

class Search < ActiveRecord::Base
  def self.class_method_options
   ['foo', 'bar']
  end

  attribute :foo, Array
  validates :foo, inclusion: class_method_options

end

That would work or you can do:

class Search < ActiveRecord::Base
  class_method_options = ['foo', 'bar']

  attribute :foo, Array
  validates :foo, inclusion: class_method_options

end
like image 82
Joeyjoejoejr Avatar answered Oct 02 '22 14:10

Joeyjoejoejr