【问题标题】:How a chaining interface like Rails ActiveRecord is built?像 Rails ActiveRecord 这样的链接接口是如何构建的?
【发布时间】:2023-03-14 22:18:02
【问题描述】:

我很感兴趣。 User.where(name: 'Foo').where(age: 20) 如何只使用一个数据库调用?

方法where 是否知道它是否是链的最后一个并改变它的行为?如果是这样,如何做到这一点?

【问题讨论】:

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


    【解决方案1】:

    每次将查询添加到其内部查询构建器后,它都会返回self

    where 不一定知道它在哪里; ActiveRecord 在查询数据库之前等待自己被枚举。示例:

    users = User.where(active: true)
    users.loaded? # false 
    users.each { }
    users.loaded? # true 
    

    eachmapfirstlast等都会触发查询加载。

    这是一个超级简单的查询构建器的示例:

    class FakeRecord
      include Enumerable
      def self.all_args
        @all_args ||= []
      end
    
      def self.where(*args)
        all_args << args 
        self
      end
    
      def self.each
        puts "Executing sql #{all_args.join(", ")}"
        yield [1, 2, 3]
      end
    end
    
    FakeRecord.where(potato: true).where(dinosaur: false).each do |thing|
      puts thing
    end
    

    【讨论】:

      猜你喜欢
      • 2011-07-29
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多