根据在我的views/post/show.htmlerb
文件中创建的时间/日期,我在显示最近创建的评论时遇到了一些麻烦。我刚刚让我posts_controller
显示最近创建的帖子,def index action
但现在在我的def show
操作中,以下代码不起作用:
@comment_date_order = Comment.find(params[:id]).comments.order('created_at DESC')
这是我完整的 posts_controller.rb 文件:
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(10)
end
def show
@comment = Comment.new
@comment_date_order = Post.find(params[:id]).comments.order('created_at DESC')
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
comments_controller.erb 文件:
class CommentsController < ApplicationController
before_action :require_user
def create
@post = Post.find(params[:post_id])
@comment = Comment.new(params.require(:comment).permit(:body))
@comment.post = @post
@comment.creator = current_user
if @comment.save
flash[:notice] = "Your comment was created!"
redirect_to post_path(@post)
else
render 'posts/show'
end
end
def edit
@comment = Comment.find(params[:id])
@post = Post.find(params[:post_id])
end
def update
@comment = Comment.find(params[:id])
if @comment.update(comment_params)
flash[:notice] = "You updated your comment!"
redirect_to post_path(@post)
else
render :edit
end
end
private
def comment_params
params.require(:comment).permit(:body)
end
def set_comment
@comment = Comment.find(params[:id])
end
end