【问题标题】:Rails with AJAX trimming contents of field使用 AJAX 修剪字段内容的 Rails
【发布时间】:2015-08-24 22:34:10
【问题描述】:

我有一个名为 Content 的模型,其中包含两个字段“之前”和“之后”。

在创建记录之前,我对字段“之前”进行了一些预处理,并将其存储在“之后”中。这里没问题。

问题是当我加载显示页面时,“之前”中的内容显示不完整。如果有 2 个或更多,我会在一段时间后修剪空白... 例如

"this is.   some text.   with many spaces.   after the periods."

视图显示“之前”看起来像这样:

"this is. some text. with many spaces. after the periods."

如果我查看 .json 版本,“之前”字段包含原始格式 - 为什么 Rails 视图(非 json)将“之前”显示为“修剪”?

这是我的 _content.html.erb

<li><%= content.before %></li>
<li><%= content.after %></li>

这是我的 show.js.erb

$("#main").html("<%= escape_javascript(render @content) %>");

这是 contents_controller.rb 中的显示定义

  respond_to :html, :json

  def show
    @content = Content.find(params[:id])
    respond_with(@content)
  end

这是我模型内容中的预处理.rb

class Content < ActiveRecord::Base

    before_validation :format_params

    def format_params
        rm_spaces = /\.\s{2,}/              # regex to rm extra spaces
        new_format = '. '                   # only one space after period
        self.after = before.gsub(rm_spaces, new_format)
    end
end

这里有一些我的意思的截图。

编辑 我相信这是自从我尝试了 Swards 推荐但它不起作用之后正在执行的代码。

这是我的 contents_helper.rb 中高亮功能的代码

def highlight_changes(text)
    highlighter = '<span style= "background: yellow">\1</span>'
    matcher = /(\.\s{2,})/
    text.gsub(matcher, highlighter).html_safe
end

这是show.html.rb中的代码

<p>
  <strong>Before:</strong>
  <!-- call the helper method to highlight changes made -->
  <%= highlight_changes @content.before %>
</p>

【问题讨论】:

    标签: ruby-on-rails ruby ajax json


    【解决方案1】:

    你可以在前面的 li 上放一个.before 类并将其添加到 css 中以查看输入的内容。

    <li class="before"><%= content.before %></li>
    <li><%= content.after %></li>
    

    在css中

    .before {
      white-space: pre;
    }
    

    【讨论】:

    • 你上了什么课?
    • 我尝试了&lt;li class="before&gt;,但没有成功,我还尝试将类直接插入到我用于突出显示的辅助函数中。将编辑帖子以显示此代码
    • 只是好奇 - 在 show.html 的内容周围尝试使用 pre 而不是 p 标签
    • 不错! show.html 中的 pre 标记正是我所需要的。谢谢!!
    【解决方案2】:

    我认为是浏览器省略了额外的空格。您可以使用 &amp;nbsp; 来创建一个空格。

    要转换你的字符串,你可以尝试

    content.before.gsub(' ', '&nbsp;').html_safe
    

    这会将每个空格替换为 &amp;nbsp;,然后告诉 rails 不要转义 html 字符 (&amp;nbsp;)。

    警告:如果before字段由用户输入,那么使用html_safe是危险的,因为它可能允许用户注入恶意代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多