所以我有一些帖子,并希望在侧边栏中显示最近的条目(这些数字在配置中设置)
我可以轻松获取最新的n条记录
- class Post < ActiveRecord::Base
- default_scope :order => "created_at DESC"
- scope :published,lambda { where("blog_entries.created_at <= ?",Time.zone.now) }
- scope :latest,lambda { |n| published.limit(n) }
- end
- @posts = Post.latest(6)
但我想要的是
- @posts = Post.published.limit(6,12)
解决方法
好的,所以答案是,我想:
- @posts = Post.published.limit(6).offset(5)
它将从第六个开始检索6个职位.
edit2:关于极限([6,12]),我觉得很奇怪:
- attr_accessor :limit_value
- def limit(value)
- relation = clone
- relation.limit_value = value
- relation
- end
- def build_arel
- ...
- arel.take(connection.sanitize_limit(@limit_value)) if @limit_value
- ...
- end
- def sanitize_limit(limit)
- if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::sqlLiteral)
- limit
- elsif limit.to_s =~ /,/
- Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
- else
- Integer(limit)
- end
- end
所以我真的不知道它如何与数组一起使用.但我显然错过了一些东西.你看到什么吗?
编辑:好尝试,但没有…;)
我不知道如果它会奏效,但是你尝试:
- @posts = Post.published.limit(6..12)
?