简体   繁体   English

我如何不包括最新记录,而是所有来自轨道对象的记录?

[英]How do i not include latest record but all record from an object in rails?

For example if i want to pull all @posts using @posts.all but i dont want to include the very last or latest record from that? 例如,如果我想使用@ posts.all拉所有@posts,但是我不想包括其中的最后或最新记录?

here is what i am trying to do, 这就是我想要做的

@posts = Post.all(Without the very very latest record that was created.) @posts = Post.all(没有创建的最新记录。)

Basically all record but not the very last record. 基本上是所有记录,但不是最后一个记录。

I think it is not worth it to try to generate a SQL query that excludes the very last element. 我认为尝试生成不包含最后一个元素的SQL查询是不值得的。 Especially a subquery might be slower than just loading all records into an Array and than excluding the last: 特别是,子查询可能比将所有记录加载到Array并排除最后一个要慢:

@posts = Post.all[0..-2]

Your other example from the comments would look like this: 注释中的其他示例如下所示:

@contact_prices = @contact.retail_prices.all.order("created_at DESC").load[0..-2]

Another option (depending on the order of your relation) might be to use offset : 另一个选择(取决于关系的顺序)可能是使用offset

@contact_prices = @contact.retail_prices.order("created_at DESC").offset(1)

This is the most direct way I think of doing what you're trying to do: 这是我想做的最直接的方法:

Post.limit(Post.count - 1)

If you want your query to allow pagination or other LIMIT queries, you could try something like 如果您希望查询允许分页或其他LIMIT查询,则可以尝试类似

Post.where("id < ?", Post.last.id)

很多答案可以解决问题,但会抛出其他选择:

@posts = Post.where("id != ?", Post.last.id)

一线AR:

Post.where.not(id: Post.last&.id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails3-使用Join的FIND(:all),如何包含JOIN中的记录? - Rails3 - FIND(:all) with a Join, how to include a record from the JOIN? 如何在Rails / Active Record中保存关联的对象 - How do i save an associated Object in Rails / Active Record Rails ActiveRecord如何找到未与特定其他记录合并的所有记录? - Rails ActiveRecord how do I find all records where the record is not joined with a particular other record? 如何从现有的 Rails 7 站点中删除活动记录? - How do I remove active record from an existing rails 7 site? Ruby on Rails + Active_Record:如何在结果中包含子计数? - Ruby on Rails + Active_Record: How do I include child counts in result? 如何通过 algolia-rails gem 在一个记录中包含多个地理位置? - How do I include several geolocations on one record via algolia-rails gem? 如何在响应中仅包含包含Ruby On Rails中关联记录的最后一条记录? - How do I include only last record in the response that contains associated records in Ruby On Rails? 如何使用squeel将联接记录包括在结果中 - How do I include the joined record in the result using squeel Rails 3-如何执行一个具有单个异常的find_all_by(从结果数组中删除单个记录)? - Rails 3 - How to do a find_all_by with a single exception (removing a single record from the resulting array)? 如何在Rails 3 Active Record查询中一起选择对象和计数? - How do I select an object and a count together in Rails 3 Active Record Query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM