我似乎无法实现这个选项:在我的应用程序上,用户也可以创建帖子和评论帖子。如果用户想要以www
格式或http
格式显示 URL,我应该如何使用rails_autolink
gem 显示它?我希望 url 是可点击的,并带你到链接。我已经安装了 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