我正在寻找ActiveRecord的来源。什么是to_a?

问题描述 投票:-2回答:2

railsdelegation.rb at v4.2.4 - railsrails

delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join, to: :to_a

断点这一行

to_a
=> undefined local variable or method `to_a' for ActiveRecord::Delegation:Module

断点停止后立即开始轨道。


委托方法document(comment)说

railsdelegation.rb at 7b92798d2fee012bf683c513fb3864a9143a6f71 - railsrails

# 通过提供符号,可以将方法委托给实例变量、类变量或常量#。

delegate run module_eval(method_def, file, line)

railsdelegation.rb at 7b92798d2fee012bf683c513fb3864a9143a6f71 - railsrails

module_eval(method_def, file, line)

断点这一行

method_def
=> "def each(*args, &block); _ = to_a;  _.each(*args, &block);rescue NoMethodError => e;  if _.nil? && e.name == :each;    raise DelegationError, \"ActiveRecord::Delegation#each delegated to to_a.each, but to_a is nil: \#{self.inspect}\";  else;    raise;  end;end"

什么是 to_a?

ruby-on-rails ruby activerecord
2个回答
1
投票

什么是to_a?

这是一个将返回一个数组的方法,如果该方法被实现的话。比如说,请看 http:/ruby-doc.orgcore-2.2.3Enumerable.html#method-i-to_a。

如果你得到的是undefined,这意味着你调用该方法的对象没有实现(也就是undefined)。

你调用to_a方法的对象是什么?这个对象不会有to_a方法。


0
投票

感谢@Bryan Oemar。https:/stackoverflow.coma335105861979953) 我发现 to_a 在rails中,我需要在动作控制器后停止断点。我需要在动作控制器后停止断点。

to_a.class
=> Array

self.method(:to_a).source_location
=> ["/Users/shingonakanishi/Documents/raku/selforderweb/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.4/lib/active_record/relation.rb", 242]

to_a railsrelation.rb中的方法

railsrelation.rb at d2315d0c3b1ede89b7cce6a77c647285359243c5 - railsrails

# Converts relation objects to Array.
def to_a
  load
  @records
end
© www.soinside.com 2019 - 2024. All rights reserved.