Question

In order to access the same array in different parts of my app, I stored the array in the corresponding Model, using class method to retrieve the array.

In the code bellow, codes are used in views (to generate the select drop down) and in the same model (to validate passed value).

class Request < ActiveRecord::Base

  validates :code, presence: true, inclusion: { in: self.codes }

  def self.codes
    return ["OBJ", "SER", "REC"]
  end

end

But using this, generates the following error:

undefined method `codes' for #<Class:0x000001074ddc50>

Even removing the self. in the inclusion, doesn't solve the problem (undefined local variable).

Do you have an idea?

Was it helpful?

Solution

Your codes method is declared after you've used it in your validation - when the validation line is executed the method has not yet been defined, hence the error.

If you place the validation after the codes method it should work.

OTHER TIPS

You can define it as a constant at a top of your model

class Request < ActiveRecord::Base
  CODES = ["OBJ", "SER", "REC"]

Than you can access it like this Request::CODES

validations will look like this

 validates :code, presence: true, inclusion: { in: CODES }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top