在我的def show动作中显示最近的评论

时间:2013-09-28 23:56:27

标签: ruby-on-rails ruby

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

1 个答案:

答案 0 :(得分:0)

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

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

class Post < ActiveRecord::Base
  has_many :comments

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

这样你也可以制作一个oldest_post方法并直接在视图中使用它

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

也是最佳做法。尝试而不是在控制器中创建太多实例变量。记住脂肪模型,瘦的控制器。