Rails 活动记录模型方法链接和获取初始输入

Rails active record model method chaining and getting the initial input

感觉应该很简单,但不确定语法是否正确。这是我在边玩边学,所以不紧迫。

我想在执行操作并从方法链获取输入的模型上编写自定义方法,而不是要求您在方法调用中设置输入参数。

鉴于我们有以下简单的 class;

class Comment < ApplicationRecord

  scope :for_user, ->(u) { where(user_id: u.id) }

  def self.do_thing
    # How do I get the results from the chain?
    # For example how do I get the IDs?
  end
end

所以我希望能够做到这一点;

Comments.for_user(current_user).do_thing

并且让 do_thing 方法知道 Comments.for_user(current_user)

的结果是什么

现在显然我可以让 do_thing 有方法参数,然后走那条路,但我正在玩和学习方法链..

感谢您的意见。

Class Comment < ApplicationRecord

  scope :for_user, ->(u) { where(user_id: u.id) }

  def self.do_thing
    # How do I get the results from the chain?
    # For example how do I get the IDs?
    self.ids
  end
end

使用self。作用域的工作方式是它们 return 一个 ActiveRecord::Relation 代理方法回调到模型的对象 class.

尽管在这种情况下该方法实际上会中断链接,因为它 return 是一个数组而不是自身或 ActiveRecord::Relation