Often I want to display a set of address fields, but only show the ones that have been filled in by the user.
For example if I have an Applicant with several address fields, then in the applicant model I will do the following:
def address
[address_1,
address_2,
address_3,
town,
county,
postcode].collect{|a| a unless a.blank? }.compact
end
The blank check makes the empty strings nil and the compact method removes the nil items. So you are left with only the fields with content output to the screen.
Then in the view I can do:
applicant.address.join("<br />")
Using the address method will output all the address fields the user has filled in, without me having to check each one individually if it has content.
The join method just put's <br />'s after each line as to create the following inside address tags:
<address>
25 The Street</br>
The City</br>
The County</br>
GU1 1AA
</address>
Comments left...
I think you could accomplish the same thing in RoR with [....].select{ |a| a.blank? }
Mark Van Holstyn at 06 Jan 07 at 11:17
I think Mark means:
[....].reject{|a| a.blank?}
Brian at 22 Jun 07 at 03:31
paks at 25 Jun 09 at 05:13
...].compact.reject(&:blank)
paks at 25 Jun 09 at 05:14
Articles Archive →
Got something to say?