我的视图表单中的文本如何自动转换为索引视图中的URL?

时间:2016-06-11 23:16:52

标签: ruby-on-rails ruby ruby-on-rails-4

如果用户在表单的description字段中添加了URL,则它在索引视图中是纯文本。如果用户在表单中添加URL,如何在索引视图中单击URL(target _blank),我将如何实现?

表格部分:

<%= form_for @win, html: { multipart: true } do |f| %>
   <% if @win.errors.any? %>
  <div id="error_explanation">
  <h2><%= pluralize(@win.errors.count, "error") %> prohibited this win from being saved:</h2>

  <ul>
  <% @win.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
</div>
<% end %>

<div class="form-group">
<%= f.label :image %>
<%= f.file_field :image, class: "form-control" %>
</div>

<div class="form-group">
<%= f.label :description %>
<%= f.text_field :description, class: "form-control" %>
</div>

<div class="form-group">
<%= f.label :public %>
<%= f.select(:public, options_for_select([['Public', 1], ['Private', 2]]), {}, {class: "form-control"}) %>
</div>

<div class="form-group">
<%= f.submit class: "btn btn-danger" %>
</div>
<% end %>

索引视图

<%= render 'pages/home' unless user_signed_in? %>

<div id="wins" class="transitions-enabled">
  <% @wins.each do |win| %>
<div class="box panel panel-default">
  <%= link_to image_tag(win.image.url(:medium)), win %>
  <div class="panel-body">
    <p><%= win.description %></p>
    <p><strong><%= win.user.username if win.user %></strong></p>
    <p class="date"><%= win.created_at.strftime("%B %d, %Y") %></p>

    <% if current_user && (win.user == current_user) %>
      <div class="actions">
        <%= link_to edit_win_path(win) do %>
          <span class="glyphicon glyphicon-edit"></span> Edit
        <% end %>
        <%= link_to win, method: :delete, data: { confirm: 'Are you sure?' } do %>
          <span class="glyphicon glyphicon-trash"></span> Delete
        <% end %>
      </div>
    <% end %>
  </div>
</div>
<% end %>
</div>

<div class="center">
 <%= will_paginate @posts, renderer: BootstrapPagination::Rails %>
</div>

1 个答案:

答案 0 :(得分:0)

使用REGEXP匹配网址格式并替换为html a标签

创建帮助

def convert_text(text)
  url_regexp = /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/
  text.gsub(url_regexp, '<a href="\0">\0</a>')
end

在索引视图中

替换<p><%= win.description %></p>

<p><%= convert_text(win.description) %></p>