LoginSignup
1
0

More than 3 years have passed since last update.

【Ruby, sinatra】textareaの改行がうまく表示できない

Last updated at Posted at 2020-04-22

textareaに改行ありのテキストを入力して、画面に表示しようとしたら見事に大失敗しました。
やろうとしていることは・・・

  1. textareaに改行ありのテキストを入力
  2. mysqlに保存
  3. Rubyでmysqlからテキストを取り出して、改行ありの状態で画面に表示

です。

環境

  • Windows10(ローカルOS)
  • CentOS7(リモートOS)
  • Oracle VM VirtualBox 6.1(仮想マシン)
  • Ruby 2.7.1p83
  • mysql

修正前の状態

markdown-mark.png

これで投稿を押すと

markdown-mark.png

このように改行が無視されています

データベースの状態

image4.png

Rubyファイルとhtmlファイル

Rubyファイル

app.rb
require "sinatra"
require "mysql2"

client = Mysql2::Client.new(host: "localhost", username: "root", password: "mysql接続時のパスワード")

post "/" do
 name = params[:name]
 comment = params[:comment]

 query = %Q{insert into training.chat(name, comment) values('#{name}', '#{comment}')}
 client.query(query)

 query = %q{select * from training.chat}
 @results = client.query(query)

 erb :index
end

他にもrequireget "/" do~endの記述もありますが、今回のテーマに直接関係ないので省かせていただきます。

htmlファイル

index.erb
<html>
  <head>
    <meta charset="UTF-8">
  </head>

  <body>
    〜〜〜〜〜中略〜〜〜〜〜

    <% @results.each do |row| %>
      <% row.each do |key, value| %>
        <%= value.gsub(/\n/, '<br/>') %>
      <% end %>
    <% end %>

    〜〜〜〜〜中略〜〜〜〜〜
  </body>
</html>

結論

index.erb
<%= value.gsub(/\n/, '<br/>') %>

改行を反映させたい値に対して.gsub(/\n/, '<br/>')をつけると改行が正常に表示されます。
【参考記事】
Sinatraでお問い合わせフォーム

markdown-mark.png
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0