我想知道是否有办法只显示数据库中有限数量的记录。
我在索引页面中有一个名为“Last items”的div容器,它们只有6个项目,我使用此代码完成了
@cars = Car.order('created_at desc').paginate :page => params[:page], :per_page => 6
并且在页面本身我刚删除了分页,所以在结果中我有6个最后添加的汽车。但使用此代码意味着它必须搜索所有记录并仅显示最后6个,但如果它在最新的第6个记录中停止搜索记录会更好。
在同一页上,我有“特别优惠”
@cars_see_special = Car.where(:special => "yes").order('rand()').paginate :page => params[:page], :per_page => 1
还必须搜索所有记录并在视图中返回一个随机的记录,并且当分页设置为1时,它只会显示一个记录,但同样,这会增加网站的负载,因为它必须通过所有记录只显示6或1。
如果您需要更多信息,请告诉我。提前谢谢。
答案 0 :(得分:1)
您可以使用Rails的限制查询:
@cars = Car.order('created_at desc').limit(6)
答案 1 :(得分:1)
创建模型级别查找器,例如:
class Car ActiveRecord::Base
def recent6
where :limit => 6, :order => 'created_at desc'
end
end
或
class Car ActiveRecord::Base
def recents(how_many)
where :limit => how_many, :order => 'created_at desc'
end
end
然后,您可以在模型级别测试它并保持控制器薄:)