Rails: Using same custom validation method for multiple models -


i have method in 3 models, i'd extract , dry things up. i'm having problem default value of attr. when field empty evaluated empty string "" instead of nil, have write conditional in method avoid adding "http" empty string.

where should put method , how can include in models?

should optimize method? if so, , how can set default attr value nil (rails/db/both)?

before_validation :format_website  def format_website   if website == ""     self.website = nil   elsif website.present? && !self.website[/^https?/]     self.website = "http://#{self.website}"   end end 

you can put method in app/models/concerns folder, example, validatable module (i.e. validatable.rb):

module concerns::validatable   extend activesupport::concern    def format_website     if website.blank?       self.website = nil     elsif !self.website[/^https?/]       self.website = "http://#{self.website}"     end   end  end 

and include in each models

include concerns::validatable 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -