ruby - Rails Model method check if field nil, if so return empty string -


in model class have method:

def full_address     address_lines = [self.address1,self.address2,self.address3].reject!(&:empty?).join(',')     fulladdress = address_lines + ", " + self.city + ', ' + self.state  + ', ' + self.zipcode     return fulladdress  end 

this easy way return address fields view them quickly.

this returns undefined method 'empty?' nil:nilclasswhen empty. how can change method work if address1, address2, address3 empty?

i guess i'm looking function like:

returnblankifnilelsevalue(self.address1) 

anything exist?

def full_address     address_lines = [self.address1.to_s,self.address2.to_s,self.address3.to_s].reject!(&:empty?).join(',')     fulladdress = address_lines + ", " + self.city + ', ' + self.state  + ', ' + self.zipcode     return fulladdress  end 

this variation returns no implicit conversion of nil string odd because in rails console can type nil.to_s , empty string.

i don't want check if each field nil , add array, i'd prefer function returned empty string if nil.

sorry nil.to_s work 2nd line needed 1 well. working rid of this.

you can, although might not wanted, remove nil objects address array using the #compact method, #empty? work...:

def full_address     [self.address1, self.address2, self.address3,         self.city, self.state, self.zipcode].compact.reject!(&:empty?).join(', ') end 

you should aware return partial address if of fields exist.

i void fault addresses (in example require first address line , city fields):

def full_address     return "" unless self.address1 && self.city && !self.address1.empty? && !self.city.empty?      [self.address1, self.address2, self.address3,         self.city, self.state, self.zipcode].compact.reject!(&:empty?).join(', ') end 

disregarding few edits made code, go @joseph's #present? validation, since you're using rails:

def full_address     return "" unless self.address1 && self.city && self.address1.present? && self.city.present?      [self.address1, self.address2, self.address3,         self.city, self.state, self.zipcode].reject!(&:present?).join(', ') end 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -