ruby - Is there a better way of validating a non model field in rails -


i have form field in ror 4 app called 'measure'. not database column, values model create child entries of own via acts_as_tree : https://github.com/rails/acts_as_tree

i have throw validation when 'measure' invalid. have created virtual attribute known measure , check validations on condition.

model somemodel  attr_accessor :measure  validates_presence_of :measure, :if => condition?  

problem when saving code, thrown validation fine. thrown same validation when trying update record in other method of model. way surpass writing code:

   # not want this, there better way?    self.measure = "somerandomvalue"     self.save  

i making virtual attribute throwing validations. there better way of throwing validations? form has other validations, not want error validations shown differently because not attribute.

i want validated when active record saved via create , update action of controller , not when being updated random method of model.

i have seen other developers in team doing similar thing , curious 1 thing - "what trying achieve doing things way doing?". see, not sure if validators should used values not serialized.

anyways, may try using format validator instead of presence, worked in team's case:

# rails 3/4 validates :measure, format: { with: /^.+$/, allow_nil: true }  # rails 2 validates_format_of :measure, :with => /^.+$/, :allow_nil => true 

you may try using allow_blank instead of allow_nil.

i rather create custom validator along lines of validates_accessor_of values know never serialized.

hth


Popular posts from this blog