Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 有没有办法访问调用singleton方法的父对象?_Ruby On Rails_Ruby_Activerecord_Rails Activerecord_Singleton Methods - Fatal编程技术网

Ruby on rails 有没有办法访问调用singleton方法的父对象?

Ruby on rails 有没有办法访问调用singleton方法的父对象?,ruby-on-rails,ruby,activerecord,rails-activerecord,singleton-methods,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,Singleton Methods,鉴于以下功能片段,我在减少数据库查询时遇到了问题: 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 < Application

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

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从以下帐户中选择帐户。* accounts.id=$1限额$2[[id,1],[LIMIT,1]]

开始

帐户加载0.3ms从帐户中选择帐户。* accounts.id=$1限额$2[[id,1],[LIMIT,1]]

测试:用户做了一些事情

帐户加载0.3ms从帐户中选择帐户。* accounts.id=$1限额$2[[id,1],[LIMIT,1]]

测试:用户做了一些事情

帐户加载0.3ms从帐户中选择帐户。* accounts.id=$1限额$2[[id,1],[LIMIT,1]]

测试:用户做了一些事情

帐户加载0.3ms从帐户中选择帐户。* accounts.id=$1限额$2[[id,1],[LIMIT,1]]

测试:用户做了一些事情

您可以看到每个用户都从数据库中获取帐户模型

我希望在Singleton方法中使用类似self.account的东西来引用原始帐户,但默认情况下,这种关系显然不存在,这就是我目前使用self.new.account的原因

是否还有其他地方可以从self内部获取保存在a中的原始帐户模型。是否要做些什么?显然,我可以在参数中传递帐户,但这似乎很乏味,尤其是如果我以后可能添加参数…

在find\u each循环中,您应该能够使用user.account

在这个循环之外,我不相信有一种记录在案的/受支持的/不会消失的-没有警告的方法来找到对象。根据您的Rails版本,self.current\u scope.proxy\u association.owner等可能会为您提供所需的答案。。。但如果可能的话,一定要选择user.account:使用私有API越多,将来的升级就越困难

另一方面,考虑使用HasyMul众多关联中定义DOAX方法——如果它不适合被称为U.Do.Objor或UsR.WabeNe: Bob. doSoad,因为那些没有关联的帐户,也许它根本不应该是顶层方法。