Question

I have some fields in my form that are not part of the model, I know how to validate those fields in the controller, but I was wondering if it is possible to validate this in the model?

If it is possible, how would I validate next? e.g.

text_field(nil, :non_model_field)
Was it helpful?

Solution

Try this:

put a virtual attribute in the model.

class MyModel < ActiveRecord::Base

   attr_accessor :non_model_field
   validates :non_model_field, presence: true # or whatever other validations you want

end

OTHER TIPS

As @wali Ali mentioned, you'll need to use a virtual attribute using the attr_accessor method to create non-persistent data

This method works by creating relevant getter & setter methods for your model, which basically create a series of attributes you can use on your model object. These attributes can then be validated, even if they are not saved, by your model:

#app/models/model.rb
Class Model < ActiveRecord::Base
    attr_accessor :test, :attribute #-> creates @model.test & @model.attribute
    validates :test, :attribute, presence: true
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top