开发者

Given @comments - how to exclude the first record

开发者 https://www.devze.com 2023-02-08 00:00 出处:网络
given @comments = Comments.last(6), which queries based on the model\'s def开发者_开发问答ault named scope.

given @comments = Comments.last(6), which queries based on the model's def开发者_开发问答ault named scope.

How can I essentially tell Rails to give me the last 6 records EXCLUDING the first record?

And if there are less than 6, just give me as many up to 6 as possible, again excluding the first record?

Thanks


I would probably use brute-force rather than SQL magics here:

@comments.delete_at(0)


class Comment < ActiveRecord::Base
  scope :excluding_first, lambda {
    first = Comment.first
    return [] unless first
    where("id <> #{first.id}")
  }
end

Since scopes compose, you can then do:

Comment.excluding_first.last(6)
0

精彩评论

暂无评论...
验证码 换一张
取 消