Reputation: 109
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)
Upvotes: 3
Views: 1189
Reputation: 76774
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
Upvotes: 2
Reputation: 2508
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
Upvotes: 5