Rails - Given @Comments - how to obtain the 2nd to last comment w/o rehitting the db

南楼画角 提交于 2019-12-23 06:48:27

问题


given @comments which can contain 1 or more records. How do I obtain the 2nd to last comment?

Thanks


回答1:


I suppose that would also be called the penultimate record:

@comments[-2]

Here are the docs1 to Ruby's interesting index operator.


1. Rubyists, note how I linked this. If you take the version out of your ruby-doc links the reference will be durable and recent.


回答2:


With any Ruby array, you can specify any range or specific index, for example if you wanted every comment from the second oldest to the second newest you could do like:

@comments[1..-2]

And to get just the second to last:

@comments[-2]

Documentation for Ruby Array#range

In Rails, if you wanted the last two comments, then you could do this, which returns an array of the last two:

@comments.last(2)

Documentation for ActiveRecord::FinderMethods




回答3:


can contain 1 or more records

This question is old, but for people coming to this now...

The other solutions will return nil if there is only one record. If you want to be sure to return a record use:

@comments.last(2)[0]



回答4:


@comments[-2]

This is pretty much the same as your last question.




回答5:


@comments = Comment.all         #Gather all comments from DB, filter as necessary.
@comments[-2]                   #Second to last comment in array


来源:https://stackoverflow.com/questions/4707507/rails-given-comments-how-to-obtain-the-2nd-to-last-comment-w-o-rehitting-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!