有没有办法访问调用单例方法的Parent对象?

问题描述 投票:0回答:1

鉴于以下功能代码段,我在减少数据库查询时遇到问题:

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中保存的原始帐户模型吗?我显然可以在一个参数中传递该帐户,但这似乎很乏味,特别是如果我稍后可以添加参数...

ruby-on-rails ruby activerecord rails-activerecord singleton-methods
1个回答
0
投票

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

在该循环之外,我不相信有找到对象的文档/支持/不会消失 - 无警告方式。根据您的Rails版本,像self.current_scope.proxy_association.owner这样的东西可能会为您提供所需的答案......但如果可能的话,请更喜欢user.account:您使用私有API的次数越多,未来的升级就越难。


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

© www.soinside.com 2019 - 2024. All rights reserved.