Ruby on Rails在两个#{string}之间添加新行

时间:2014-07-08 13:58:30

标签: ruby-on-rails string line add between

我为名为:settore_scientifico_progetto的模型的文字属性和三个字符串属性:macrocat:cat:microcat

class Modulo1 < ActiveRecord::Base
  before_create :set_settore_scientifico_progetto
  before_update :update_settore_scientifico_progetto

  private      
  def set_settore_scientifico_progetto
    self.settore_scientifico_progetto = "#{macrocat}\n#{cat}\n#{microcat}" 
  end

  def update_settore_scientifico_progetto
    self.settore_scientifico_progetto = "#{macrocat}\n#{cat}\n#{microcat}"
  end

我想在我键入\n的位置添加一个新行,但我发布的代码为我提供了输出 macrocat cat microcat

我希望如下:

  

macrocat
  猫
  的Microcat

输出显示在show.html.erb

<div class="form-field">  
  <h3>Settore scientifico:</h3>
  <p><%= @modulo1.settore_scientifico_progetto %></p>
</div>

1 个答案:

答案 0 :(得分:4)

Rails专门为此目的提供了一个名为simple_format的帮助器。

<%= simple_format @modulo1.settore_scientifico_progetto %>

这将输出以下HTML:

<p>macrocat<br/>
  cat<br/>
  microcat
</p>

您的浏览器会像这样呈现:

  

macrocat
  猫
  的Microcat

这似乎正是您正在寻找的,它会为您清理HTML。 (自定义输出的选项,例如更改换行标记或HTML属性,为listed in the docs。)

P.S。使用上面提到的gsub...html_safe方法非常危险。如果您的应用接受了您正在打印的任何属性的用户输入,则在这些值上调用html_safe意味着它们将不会被ActionView清理,并且恶意用户可能会在视图中注入代码,使您的应用容易受到攻击跨站点脚本(XSS)攻击。 Here's a good primer关于Rails中html_safe的来龙去脉。