我在 model 中写了两个 scope
scope :next, -> (this_id){where("id > ?", this_id).order(id: :asc).first}
scope :previous, -> (this_id){where("id < ?", this_id).order(id: :desc).first}
controller
@next = Article.enabled.tec_articles.next(params['id'])
@previous = Article.enabled.tec_articles.previous(params['id'])
当 next 或者 previous 查不到数据的时候,后台日志:
Article Load (3.4ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`enabled` = TRUE AND `articles`.`category` = 'tec' AND `articles`.`id` = 5 LIMIT 1
Article Load (3.4ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`enabled` = TRUE AND `articles`.`category` = 'tec' AND (id > '5') ORDER BY `articles`.`id` ASC LIMIT 1
Article Load (3.5ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`enabled` = TRUE AND `articles`.`category` = 'tec' AND (id < '5') ORDER BY `articles`.`id` DESC LIMIT 1
#<Article id: 5, tag: "rails", title: "路由拆分", content: "* 当项目路由越来越多,routes文件会变得拥挤,难以管理,这时候就需要我们对路由文件进行拆分\r\n...", reading_time: 0, category: "tec", attachment: nil, enabled: true, created_at: "2018-09-06 09:34:59", updated_at: "2018-09-06 09:38:37">
#<Article id: 4, tag: "rails", title: "rails中的ActiveSupport::Concern", content: "#### ActiveSupport::Concern的作用以及由来\r\n在rails项目中,如果mo...", reading_time: 0, category: "tec", attachment: nil, enabled: true, created_at: "2018-09-05 10:04:43", updated_at: "2018-09-06 09:51:28">
Article Load (3.5ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`enabled` = TRUE AND `articles`.`category` = 'tec' LIMIT 11
#<ActiveRecord::Relation [#<Article id: 4, tag: "rails", title: "rails中的ActiveSupport::Concern", content: "#### ActiveSupport::Concern的作用以及由来\r\n在rails项目中,
如果mo...", reading_time: 0, category: "tec", attachment: nil, enabled: true, created_at: "2018-09-05 10:04:43", updated_at: "2018-09-06 09:51:28">, #<Article id: 5, tag:
"rails", title: "路由拆分", content: "* 当项目路由越来越多,routes文件会变得拥挤,难以管理,这时候就需要我们对路由文件进行拆分\r\n...", reading_time: 0, category:
"tec", attachment: nil, enabled: true, created_at: "2018-09-06 09:34:59", updated_at: "2018-09-06 09:38:37">]>
从日志来看,当查不到数据的时候就为自动去去除了相关查询条件返回结果,这是什么机制啊?其实我本意是想让它返回 nil 的