Accessor class methods from include check

I would like to include a class method as my parameters when using include check:

class Search < ActiveRecord::Base

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

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

      

However I am getting 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 include validator. How can I access class_method_options

from the inclusion check?

+3


source to share


3 answers


It hasn't been defined yet.

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

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

end

      



It will work or you can:

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

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

end

      

+6


source


You should do like this:



class Search < ActiveRecord::Base

  attribute :foo, Array
  validates :foo, inclusion: {in: :class_method_options }

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

      

0


source


Given :in

accepts Proc, I ended up with

validates :foo, inclusion: { in: Proc.new { |search| search.class.class_method_options } }

      

0


source







All Articles