gpt4 book ai didi

ruby-on-rails - 在 Rails 中添加 created_at DESC 功能

转载 作者:数据小太阳 更新时间:2023-10-29 06:45:14 24 4
gpt4 key购买 nike

我有一个带有帖子和评论模型的应用程序。在我的索引操作/ View 中,我遍历帖子并从最近创建时间到最早创建时间显示它们。我的评论嵌套在我的帖子中,因此在我的帖子显示操作/ View 中,我想遍历评论并让它们显示从最近创建到最早创建的时间。如果我在我的 post.rb 文件中创建一个方法,我似乎只能让它工作。我有这个:

post.rb:

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

在我的帖子展示 View 中,我可以遍历帖子评论并且效果很好:

<% @post.newest_comments.each do |comment|
<% end %>

但我想在 Controller 层设置此功能,但我不知道如何设置。这是我在我的帖子 Controller 中的 show Action :

  def index
@posts = Post.all.order("created_at DESC")
end

def show
@comment = Comment.new
@comments = Comment.all.order("created_at DESC")
end

现在我更新后的展示 View :

<% @post.comments.each do |comment| %>
<% end %>

@post var 是因为我之前的操作。所以我的问题是,为什么我不能通过简单地在我的展示 View 中调用它来访问我的展示后 View 中的这个 ivar?

最佳答案

随着updates to Rails你可以避免像这样使用 created_at DESC SQL 语法:

@comments = @post.comments.order(created_at: :desc)

关于ruby-on-rails - 在 Rails 中添加 created_at DESC 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20650403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com