0

鉴于以下功能片段,我无法减少数据库查询:

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吗?我显然可以在参数中传递帐户,但这似乎很乏味,特别是如果我以后可以添加参数...

4

1 回答 1

0

在你的find_each循环中,你应该能够使用user.account.

在那个循环之外,我不相信有一个记录/支持/不会在没有警告的情况下消失的方法来找到对象。根据您的 Rails 版本,类似的东西self.current_scope.proxy_association.owner可能会为您提供所需的答案……但user.account如果可能的话,请更喜欢:您使用私有 API 的次数越多,未来升级的难度就越大。


或者,考虑使用关联扩展来仅在关联中定义您的do_something方法has_many——如果它不适合被称为User.do_somethingor User.where(name: "Bob").do_something(因为那些没有关联的account),也许它毕竟不应该是顶级方法。

于 2018-06-21T13:00:33.850 回答