新手问题 关于 rails 查询:

sanm1992 · 2018年09月08日 · 最后由 sanm1992 回复于 2018年09月08日 · 1403 次阅读

我在 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 的

楼主对 scope 的使用是存在问题的:源码

  1. scope intended to return an ActiveRecord::Relation object
  2. if it returns nil or false, an all scope is returned instead

抛开本身不说

nextprevious 的调用者应该是 实例本身。翻译出来:我的前任我的后任 (PS: 所以没有前任也正常对吧)

如果楼主非要执意勉强,那么定义 类方法 是最好的

so_zengtao 回复

非常感谢,我确实没太多了解 scope,就之前浏览过一下源码,🙏

3 楼 已删除
sanm1992 关闭了讨论。 09月08日 12:41
需要 登录 后方可回复, 如果你还没有账号请 注册新账号