我似乎无法实现此选项:在我的应用中,用户也可以创建帖子并对帖子发表评论。如果用户想要以www
格式或http
格式显示网址,我应该如何使用rails_autolink
gem显示该网址?我希望网址可以点击并转到链接。我已经安装了gem并将其添加到我的帖子控制器中。另一位用户向我提出了gem,但我不明白如何实现它。用户从帖子显示模板创建评论。宝石是否需要在show template
或posts_controller
?
这是我的帖子show.html.erb
:
<div class="page-header">
<h2>
<%= @post.title %>
<small>
posted by <%= link_to @post.creator.username %> <%= time_ago_in_words(@post.created_at) + ' ago' %>
| <%= link_to 'go to link', fix_url(@post.url) %>
<% if logged_in? && (@post.creator == current_user) %> |
<%= link_to 'edit', edit_post_path(@post) %> |
<i class="icon-user icon"></i>
<% end %>
</small>
</h2>
</div>
<h3><%= @post.description %></h3>
<%= render 'shared_partials/errors', errors_obj: @comment %>
<%= form_for [@post, @comment] do |f| %>
<%= f.text_area :body, :class=> "span4", :placeholder=> "Comment goes here", :rows => "7" %>
</br>
<div class="button">
<%= f.submit "Create a comment", class: 'btn btn-primary' %>
</div>
<% end %>
<div class="page-header">
<h4>All Comments</h4>
</div>
<% @post.newest_comments.each do |comment| %>
<div class="comments">
<h5><%= comment.body %></h5>
<li>
<small class="muted">
posted by <%= link_to comment.creator.username %> <%= time_ago_in_words(comment.created_at) + ' ago' %>
<% if logged_in? && (comment.creator == current_user) %> |
<%= link_to 'edit', edit_post_comment_path(@post, comment) %> |
<i class="icon-user icon"></i>
<% end %>
</small>
</li>
</div>
<% end %>
和我的posts_controller:
require 'rails_autolink'
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :vote]
before_action :require_user, only: [:new, :create, :edit, :update, :vote]
before_action :require_creator, only:[:edit, :update]
def index
@posts = Post.page(params[:page]).order('created_at DESC').per_page(15)
end
def show
@comment = Comment.new
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.creator = current_user
if @post.save
flash[:notice] = "You created a post!"
redirect_to posts_path
else
render :new
end
end
def edit
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
flash[:notice] = "You updated the post!"
redirect_to post_path(@post)
else
render :edit
end
end
def vote
Vote.create(voteable: @post, creator: current_user, vote: params[:vote])
respond_to do |format|
format.js { render :vote } # Renders views/posts/vote.js.erb
end
end
private
def post_params
params.require(:post).permit(:url, :title, :description)
end
def set_post
@post = Post.find(params[:id])
end
def require_creator
access_denied if @post.creator != current_user
end
end
答案 0 :(得分:0)
我不完全确定rails_autolink
会做你想要完成的事情。基本上,per the documentation,gem将输出文本中的URL插入到将URL作为文本包含在内的超链接。默认情况下,标记输出为已清理的html_safe
字符串:
auto_link("Go to http://www.rubyonrails.org and say hello")
# => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and say hello"
您应该直接在视图/模板中使用它,而不应该需要在我们的控制器中使用它。 Rails通常在应用程序加载时需要gem依赖项,因此您不需要在运行时包含它们。