【问题标题】:Counting created comments for all Posts计算所有帖子的已创建评论
【发布时间】:2023-03-28 02:06:02
【问题描述】:

帖子 #2 有 1 条评论。当我尝试为帖子 #1 创建 first 评论时,我得到

/posts/1/cmets/2

在评论的索引页面上,它为所有帖子列出了相同的 cmets,无论它们的 ID 是什么。


cmets_controller

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.build(comment_params)
    @comment.user = current_user

    respond_to do |format|
      if @comment.save
        format.html { redirect_to [@post, @comment], notice: 'It was successfully created.' }
        format.json { render action: 'index', status: :created, location: @comment }
      else
        format.html { render action: 'new' }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

路线

resources :posts do
    resources :comments
end

【问题讨论】:

  • 请分享 index CommentsController 的操作。另外,分享帖子和 cmets 的路线。
  • 您在哪里设置@post 用于索引操作。另外,分享routes.rb的内容。
  • 让我们在聊天chat.stackoverflow.com/rooms/48530/ror讨论这个问题

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

在评论的索引页面上,它为所有帖子列出了相同的 cmets, 不管他们的身份如何。

您必须定义CommentsController#index 如下: 定义索引 @cmets = 评论.all 结尾 这就是为什么在评论的索引页面上,您会看到所有帖子的相同 cmets。

假设你有嵌套路由:

resources :posts do
  resources :comments
end

更新CommentsController#index如下:

def index
  @post = Post.find(params[:post_id])
  @comments = @post.comments
end

【讨论】:

    【解决方案2】:

    您应该删除数据库并重新创建它,以便从头开始计数。

    rake db:drop
    rake db:create
    

    这完全是关于数据库中键(如:id)的自动递增功能。

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 2015-09-20
      • 2017-07-03
      • 1970-01-01
      相关资源
      最近更新 更多