Ruby on rails 如何使rails表单响应超链接?
我正在学习MichaelHartl的Rails教程,并完成了有关创建MicroPost的部分。我想知道是否有人知道如何使micropost表单响应超链接。例如,当用户在micropost中键入Ruby on rails 如何使rails表单响应超链接?,ruby-on-rails,ruby,hyperlink,Ruby On Rails,Ruby,Hyperlink,我正在学习MichaelHartl的Rails教程,并完成了有关创建MicroPost的部分。我想知道是否有人知道如何使micropost表单响应超链接。例如,当用户在micropost中键入“时,我希望链接处于活动状态。任何帮助都将不胜感激 micropost\u控制器.rb class MicropostsController < ApplicationController before_action :signed_in_user, only: [:create, :destroy]
“
时,我希望链接处于活动状态。任何帮助都将不胜感激
micropost\u控制器.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
<%= 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 %>
class MicropostsController
microspost.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
class Micropost{order('created_at DESC')}验证:content,
presence:true,长度:{maximum:140}验证:user\u id,
存在:真正的终结
...
结束
microspost_form.html.erb
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
<%= 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 %>
您可以使用helper方法并将锚(a
)标记作为唯一允许的标记传入。你在他们创建帖子时不使用它,而是在视图中显示micropost时使用它
app/views/microposts/show.html.erb
<%= sanitize micropost.content, tags: ['a'] %>
(我不知道你是如何展示micropost的内容的,但这应该会给你一个想法)
这比其他选项(如html\u safe
)更安全,因为您可以实际控制允许用户输入的html标记