鉴于以下功能片段,我无法减少数据库查询:
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) 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]]
测试:用户做了某事
帐户负载 (0.3ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
测试:用户做了某事
您可以看到 Account 模型是从每个用户的数据库中获取的!
我希望self.account
在 Singleton 方法中使用类似的东西来引用原始帐户,但是默认情况下显然不存在这种关系,这就是我目前使用self.new.account
.
我还有其他地方可以a
从内部获取保存的原始 Account 模型self.do_something
吗?我显然可以在参数中传递帐户,但这似乎很乏味,特别是如果我以后可以添加参数...