0

根据在我的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
4

1 回答 1

0

首先,如果您还没有,则需要 Post 和 Comment 之间的关系。

我只会在 Post 模型中创建一个 def 。

class Post < ActiveRecord::Base
  has_many :comments

  def newest_comments
    self.comments.order('created_at DESC')
  end
end

这样你也可以创建一个 old_post 方法并直接在视图中使用它

<%= @post.newest_post.each do |comment| %>

也作为最佳实践。尽量不要在控制器中创建太多实例变量。记住胖模型,瘦控制器。

于 2013-09-29T00:46:59.610 回答