【问题标题】:What is the difference with find_by() from the core and the one from the FinderMethods?核心中的 find_by() 和 FinderMethods 中的 find_by() 有什么区别?
【发布时间】:2016-07-21 18:12:43
【问题描述】:

目前我正在研究一个 gem,它会覆盖 ActiveRecords where。通过努力,我偶然发现了两个不同的find_by 实现。一个在core 中,它使用某种缓存,而来自FinderMethods 模块的一个直接调用where。这两种实现有什么区别?什么时候用?

【问题讨论】:

  • 也许只有我一个人,但重写像 where 这样的 Rails 核心方法对我来说是个糟糕的主意......
  • 嗯,像globalize 这样的流行宝石也在这样做。幸运的是 ActiveRecord 有很多测试。

标签: ruby-on-rails ruby activerecord rails-activerecord


【解决方案1】:

我认为是这样的:当你使用这样的东西时:

User.find_by(...)

ActiveRecord::Core#find_by 被调用,因为核心包含在您继承的 Base 中。

但如果你这样做:

User.first.products.find_by(...)

ActiveRecord::Relation(包括FinderMethodshere)将调用FinderMethods#find_by

我不知道为什么会这样实现,但我确信这是有原因的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2014-10-12
    • 2017-09-04
    • 2020-06-10
    相关资源
    最近更新 更多