我很感兴趣。 User.where(name: 'Foo').where(age: 20)
如何仅使用一个数据库调用?
where
方法是否知道它是否是链的最后一个并改变它的行为?如果可以,如何实现?
最佳答案
每次将查询添加到其内部查询构建器后,它都会返回 self
。
where
不一定知道它在哪里; ActiveRecord 在查询数据库之前等待自身被枚举。示例:
users = User.where(active: true)
users.loaded? # false
users.each { }
users.loaded? # true
each
、map
、first
、last
等都会触发查询加载。
这是一个 super 简单的查询构建器的例子:
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
关于ruby-on-rails - 如何构建像 Rails ActiveRecord 这样的链接接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61898993/