如何通过 ActiveRecord 将当前作用域用于自定义构建器 class 方法

How to use current scope for custom builder class methods via ActiveRecord

我在每个 Account 上有很多 Messages,并且想像这样使用自定义生成器:Account.find(x).messages.send_and_create('confirm').

为此,我需要访问 send_and_create 中的 account_id 值,以便在构建 message 时设置该值。但是我无法找到一种方法来在 Message 上编写此 class 方法来获取该值。

关联扩展是解决这个问题的方法:

has_many :messages do 
  def send_and_create(type)
    ...
  end
end

Rails source