2014-11-20 38 views
1

我遵循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

您可以使用sanitize輔助方法,並將錨點(a)標記作爲唯一允許的標記傳入。你不使用它的時候,他們創造了後,你使用它時,你是顯示在視圖

app/views/microposts/show.html.erb

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

的微柱(我不知道究竟你是如何顯示的內容微博,但這應該給你一個想法) 這比其他選項如html_safe更安全,因爲你實際上可以控制哪些html標籤,你將允許用戶能夠輸入。

+0

它工作。謝謝。 – masaaki 2016-05-25 11:46:35