【问题标题】:How does ActiveRecord::Relation class act like Array?ActiveRecord::Relation 类如何像数组一样工作?
【发布时间】:2017-10-04 05:48:21
【问题描述】:

ActiveRecord::Relation 类如何像数组一样工作?

例如,

User.all
=> #<ActiveRecord::Relation [#<User id: 1, name: "Alex", nickname: "leha", created_at: "2017-05-05 12:36:31", updated_at: "2017-05-05 12:36:31">]>   

它返回 ActiveRecord::Relation,其行为类似于 Array。

如果我创建自己的课程MyClass

class MyClass
  attr_accessor :relation
  def initialize(options)
    @relation = options
  end
end

m = MyClass.new [1,2,3]
=> #<MyClass:0x007ffa3f9ab730 @relation=[1, 2, 3]>

问题是如何制作像 ActiveRecord::Relation 这样的类?

【问题讨论】:

  • 哦,问题不是关于如何使用AR,我是问如何制作像ActiveRecord::Relation这样的子类,它的作用类似于数组。
  • 你所说的“像数组一样”是什么意思?
  • AR中你可以使用User.all[0]。在我的情况下MyClass.new([1,2,3]).relation[0]。如何在我可以使用MyClass.new([1,2,3])[0] 的地方上课?
  • 为什么不将:[] 方法委托给relation?查看Forwardable module in ruby stdlib.
  • @GlebVishnevsky 还有,只是为了澄清一下,您不是在这里继承 AR,而是将其包装到您自己的类中。

标签: ruby-on-rails arrays ruby activerecord


【解决方案1】:

因为包含模块Enumerable,它可以对类进行排序。 Arrays 实现的大多数方法都来自该特定模块。所以如果你想创建一个像数组一样的类,你应该实现Enumerable

正如您在 Active Record 的以下代码中看到的,您可以注意到它何时包含在类中:

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation.rb#L15

参考资料:

  1. https://ruby-doc.org/core-2.4.1/Enumerable.html
  2. https://ruby-doc.org/core-2.4.1/Array.html#class-Array-label-Iterating+over+Arrays

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    相关资源
    最近更新 更多