如何响应超链接制作rails表格?

时间:2014-11-20 22:51:18

标签: ruby-on-rails ruby hyperlink

我正在关注Michael Hartl的Rails教程并完成了关于创建微博的部分。我想知道是否有人知道如何使微博形式响应超链接。例如,当用户在微博中键入"<a href="http://www.w3schools.com/html/">Visit our HTML tutorial</a>"时,我希望链接处于活动状态。任何帮助,将不胜感激。

micropost_controller.rb

class MicropostsController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy


def create
  @micropost = current_user.microposts.build(micropost_params)
  if @micropost.save
  flash[:success] = "Micropost created!"
  redirect_to root_url
else
  @feed_items = []
  render 'static_pages/home'
end
end

def destroy
  @micropost.destroy
  redirect_to root_url
end

private 

  def micropost_params
    params.require(:micropost).permit(:html)
end

def correct_user
  @micropost = current_user.microposts.find_by(id: params[:id])
  redirect_to root_url if @micropost.nil?
end
end

micropost.rb

 class Micropost < ActiveRecord::Base   
   belongs_to :user  
   default_scope -> { order('created_at DESC') }   validates :content,
   presence: true, length: { maximum: 140 }   validates :user_id,
   presence: true end

 ...
 end

micropost_form.html.erb

<%= form_for(@micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Compose new micropost..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

1 个答案:

答案 0 :(得分:1)

您可以使用sanitize辅助方法并将锚点(a)标记作为唯一允许的标记传递。您在创建帖子时不使用它,在视图中显示微博时使用它

app/views/microposts/show.html.erb

<%= sanitize micropost.content, tags: ['a'] %>

(我不确切知道你是如何展示微博的内容的,但这应该给你一个想法) 这比html_safe等其他选项更安全,因为您实际上可以控制哪些html标签可以让用户输入。