【问题标题】:I am looking for a source each of ActiveRecord. What is to_a?我正在寻找每个 ActiveRecord 的来源。 to_a 是什么?
【发布时间】:2015-11-03 22:41:40
【问题描述】:

rails/delegation.rb at v4.2.4 · rails/rails

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

rails 启动后断点立即停止。


委托方法文档(评论)说

rails/delegation.rb at 7b92798d2fee012bf683c513fb3864a9143a6f71 · rails/rails

# 方法可以委托给实例变量、类变量或常量
# 通过将它们作为符号提供:

delegate 运行module_eval(method_def, file, line)

rails/delegation.rb at 7b92798d2fee012bf683c513fb3864a9143a6f71 · rails/rails

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

【问题讨论】:

  • 你的问题到底是什么?
  • to_a => undefined ...但是Ruby可以to_a在Enumerable中吗?
  • 欢迎来到 Stack Overflow。请不要使用任意粗体文本。这就像输入所有大写字母一样糟糕。 to_a 是对象的基本构建块,继承自 Enumerable。也许您需要通读各种核心类的文档?此外,作为一个问题,您的标题也应该是您问题的第一行。 "How to Ask"

标签: ruby-on-rails ruby activerecord


【解决方案1】:

to_a 是什么?

如果方法被实现,这是一个返回数组的方法。 例如:http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-to_a

如果你得到一个未定义的,这意味着该方法没有为你调用该方法的对象实现(又名未定义)。

你调用 to_a 的对象是什么?该对象将没有 to_a 方法。

【讨论】:

  • 运行时是否包含委托后 Enumerable 的 to_a?我想知道在哪里?
  • 你想在这里完成什么?您何时以及在什么对象上尝试调用此 to_a 方法?
  • 哦,我明白了。我运行 rails start,所以 to_a 是 undef。但我的控制器to_a.class => Array
  • 在回答中我们不应该说“你调用 to_a 的对象是什么?”那是邀请 OP 加入对话,但答案是陈述,而不是对话。对原始问题的评论会更合适。
【解决方案2】:

感谢@Bryan Oemar。(https://stackoverflow.com/a/33510586/1979953)
我在 rails 中找到了to_a
我需要在动作控制器之后停止断点。

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 rails/relation.rb 中的方法

rails/relation.rb at d2315d0c3b1ede89b7cce6a77c647285359243c5 · rails/rails

# Converts relation objects to Array.
def to_a
  load
  @records
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2012-01-18
    相关资源
    最近更新 更多