鉴于以下功能代码段,我在减少数据库查询时遇到问题:
class User < ApplicationRecord
belongs_to :account
def self.do_something
self.find_each do |user|
puts "#{self.new.account.name}:#{user.name} did something"
end
end
end
class Account < ApplicationRecord
has_many :users
end
a = Account.first
puts 'starting'
a.users.do_something
帐户加载(0.4ms)选择“帐户”。* FROM“帐户”WHERE“帐户”。“id”= $ 1 LIMIT $ 2 [[“id”,1],[“LIMIT”,1]]
开始
帐户加载(0.3ms)SELECT“accounts”。* FROM“accounts”WHERE“accounts”。“id”= $ 1 LIMIT $ 2 [[“id”,1],[“LIMIT”,1]]
测试:用户做了一些事情
帐户加载(0.3ms)SELECT“accounts”。* FROM“accounts”WHERE“accounts”。“id”= $ 1 LIMIT $ 2 [[“id”,1],[“LIMIT”,1]]
测试:用户做了一些事情
帐户加载(0.3ms)SELECT“accounts”。* FROM“accounts”WHERE“accounts”。“id”= $ 1 LIMIT $ 2 [[“id”,1],[“LIMIT”,1]]
测试:用户做了一些事情
帐户加载(0.3ms)SELECT“accounts”。* FROM“accounts”WHERE“accounts”。“id”= $ 1 LIMIT $ 2 [[“id”,1],[“LIMIT”,1]]
测试:用户做了一些事情
您可以看到每个用户从数据库中获取帐户模型!
我希望在Singleton方法中使用类似self.account
的东西来引用原始帐户,但默认情况下这种关系显然不存在,这就是我目前正在使用self.new.account
的原因。
还有其他地方我可以从a
内部获取self.do_something
中保存的原始帐户模型吗?我显然可以在一个参数中传递该帐户,但这似乎很乏味,特别是如果我稍后可以添加参数...
在你的find_each
循环中,你应该能够使用user.account
。
在该循环之外,我不相信有找到对象的文档/支持/不会消失 - 无警告方式。根据您的Rails版本,像self.current_scope.proxy_association.owner
这样的东西可能会为您提供所需的答案......但如果可能的话,请更喜欢user.account
:您使用私有API的次数越多,未来的升级就越难。
或者,考虑使用association extensions仅在do_something
关联中定义你的has_many
方法 - 如果它不适合被称为User.do_something
或User.where(name: "Bob").do_something
(因为那些没有相关的account
),也许它不应该是顶级的毕竟方法。