Reputation: 7634
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?
Upvotes: 0
Views: 330
Reputation: 101
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 }
Upvotes: 1
Reputation: 84114
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.
Upvotes: 1