ファイルで作成された日時に基づいて、最近作成されたコメントを表示するのに少し問題があり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