I’m trying to create a simple method in a model to create a multi-line
address from discrete input fields:
def full_address
[address1, address2, address3, city, postcode].compact.join(’\n’)
end
However, the line break is appearing in the view as the string “\n”,
not a line break ( “address1\naddress2\naddress3\ncity\npostcode”). I
can’t figure out what I need to do to get line breaks. What am I
missing?
Also, compact only seems to remove null values, not empty values. The
form I use converts null values to empty values when it is saved, so I
end up with something like this if address3 is empty:
Also, compact only seems to remove null values, not empty values. The
form I use converts null values to empty values when it is saved, so I
end up with something like this if address3 is empty:
address1, address2, , city, postcode
Is there a way around this?
Thanks for any help.
You want double quotes, not single quotes around the \n. Not sure if
this is the best way but gsub can get rid of the empty values:
Thanks for the replies. I still have the same issue with the html
output if I use double quotes, though. The “\n” is being rendered as
white space in the html, not line breaks. The html source shows that
line breaks are being passed through, but they are not being converted
to tags, which is what I’d need.
I get the desired html output if I put this in the model:
def full_address
[address1, address2, address3, city,
postcode].reject(&:blank?).join(" ")
end
and this in the view:
<%= address.full_address %>
Note the absence of =h - if I put =h in the view, I just get the
escaped characters of course. However, I want to use =h to handle any
issues related to html and display of address data.
It doesn’t seem “right” to put html code into a method in the model,
so I’m not happy with this solution. I’m missing something here. Any
thoughts would be appreciated.
Whitespace in HTML is ignored as per the HTML spec. This is a feature
of HTML, not any kind of bug in rails. Use simple_formet() to convert
newlines to or