Enter line breaks in rails text_area → display as it is.

I just referred to this article lol https://qiita.com/kamotetu/items/1aa94994985c720668e4

with form_for and form_with Line breaks when entering text → I can't do it at all! It became. I want to display it as it is.

problem

input form

new.html.erb


<div class="from-group mb-4">
   <%= f.label :introduction, "Introduction", class: "form-label" %><br />
   <%=f.text_area :introduction, class: "form-control", id:"user-introduction", size: "90x5", maxlength: "1000", placeholder: "Write an introductory text"%>
</div>

Enter a post スクリーンショット 2020-12-17 21.16.32.png display

show.html.erb


<%[email protected]%>

Then スクリーンショット 2020-12-17 21.39.24.png I can't break a line. I want to solve this.

Solution

show.html.erb


<%=safe_join(@user.introduction.split("\n"),tag(:br))%>

Just change it to スクリーンショット 2020-12-17 21.45.02.png I did well!

This description is

It becomes possible.

By the way

When the input home was not validated, an error occurred if it was sent blank. In such a case

show.html.erb


<%if @user.introduction.nil? %>   #If the introductory text remains "empty", an error will occur, so nil?=Add when true
  <%[email protected]%>       #No validation
<% else %>
  <%=safe_join(@user.introduction.split("\n"),tag(:br))%>    #If the introductory text is not "empty", it will be reflected normally
<%end %>

I solved it with.

Recommended Posts

Enter line breaks in rails text_area → display as it is.
How to display the text entered in text_area in Rails with line breaks
Display Flash messages in Rails
Isn't it reflected even if the content is updated in Rails?
Implement star evaluation function in Rails 6 (Webpacker is installed as standard)
Data is not registered in Rails.
[Rails / simple_format] Helper method that reflects line breaks entered in the form
Continuation ・ Active hash that can be handled as data even if it is not in the database ~ Display