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



这感觉应该很简单,但我不确定正确的语法。这是我在玩耍和学习,所以这并不紧迫。

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

假设我们有以下简单类;

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。作用域的工作方式是返回一个ActiveRecord::Relation对象,该对象代理方法调用回模型类。

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

最新更新