【问题标题】:Comments Section Ordering The Comments Newest At Top Instead Of Bottom评论部分将最新的评论排序在顶部而不是底部
【发布时间】:2020-01-14 09:02:21
【问题描述】:

几周前我部署了一个网络应用程序,用户可以在其中发布其他人可以评论的帖子。 cmets 将按最旧的在顶部和最新的在底部进行排序。这一直很好,直到大约 2 周前,我添加了编辑帖子的功能,从那时起,cmets 并一直以相反的方式对所有新帖子进行排序。即最新的在顶部。

我完成了我的提交,但看不到我可以做些什么来导致更改。最糟糕的是它仍然可以正常工作,因为我希望它在本地很难调试。

评论控制器:

class CommentsController < ApplicationController

  before_action :logged_in_user, only: [:create, :destroy]

  def create
    @micropost = Micropost.find_by(id: params[:micropost_id])
    @comment = 
   @micropost.comments.create(params[:comment].permit(:name,:body))
    @comment.name = current_user.name
    if @comment.save
      flash[:success] = "Comment Posted"
    end
    redirect_to request.referrer
 end

 def destroy
   @comment = Comment.find(params[:id])
   @comment.destroy
   redirect_to request.referrer
 end

end

Microposts 控制器的节目:

  def show
    @micropost = Micropost.find_by(id: params[:id])
    @post = Micropost.includes(:comments).find(params[:id])
    @micropost.punch(request)
    end

我尝试将.order(:created_at =&gt;:desc) 添加到上面的@post 中,但没有任何区别。我做了 :asc 来测试,但 cmets 不会重新排序。我已经在其他地方成功使用了.order。

在 Micropost 视图上呈现的评论视图:

<li>
  <ol class="microposts">
    <% @post.comments.each do |comment| %>
      <li>
        <article class="article-container-full">
          <%=  comment.name %>
          <hr>
        <%= simple_format(comment.body) %>
          <hr>
          <p class="posted-time">
            Posted <%= time_ago_in_words(comment.created_at) %> ago
          </p>
        </article>
        <br>
       </li>
      </ol>
    <% end %>
</li>

评论表单视图

<%= form_for([@micropost, @micropost.comments.build]) do |f| %>
  <br>

  <h4 class="article-content">
    <%= f.hidden_field :name ,value: current_user.name %>
    <%= "Commenter: #{current_user.name}" %>
  </h4>

  <p>
    <%= f.text_area :body, rows:"4" ,required: true %>
  </p>

  <br>
   <p>
   <%= f.submit class: 'submit-button' %>
   </p>

  <% end %>

微博查看评论渲染

 </li>
  <h1 class="article-container-header"> Comments</h1>
 <article>
   <%= render "comments/comment" %>
 </article>
 <% if logged_in? %>
  <article class="article-container-full">
   <%= render 'comments/form' %>
 </article>
 <% end %>

我尝试在几个地方使用.order(:created_at =&gt;:desc) 或.order(:created_at =&gt;:asc),但无济于事。

欢迎所有建议。

【问题讨论】:

    标签: ruby-on-rails ruby comments


    【解决方案1】:

    您需要订购 cmets。

    在微博视图中:

    <% @post.comments.order(created_at: :asc).each do |comment| %>
      ..
    <% end %>
    

    【讨论】:

      【解决方案2】:

      在你的 show 方法中:

      @post = Micropost.find(params[:id])
      @comments = @post.includes(:comments).order('comments.created_at DESC')
      

      然后您可以在 HTML 文件中迭代 @cmets。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-31
        • 1970-01-01
        • 2011-02-12
        • 2014-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-03
        相关资源
        最近更新 更多