简体   繁体   English

Rails和ActiveRecord:将方法附加到从ActiveRecord :: Base继承的模型

[英]Rails & ActiveRecord: Appending methods to models that inherit from ActiveRecord::Base

I have a standard ActiveRecord model with the following: 我有一个标准的ActiveRecord模型,具有以下内容:

class MyModel < ActiveRecord::Base
  custom_method :first_field, :second_field
end

At the moment, that custom_method is picked up by a module sent to ActiveRecord::Base. 目前,该custom_method被发送到ActiveRecord :: Base的模块选中。 The functionality basically works, but of course, it attaches itself to every model class, not just MyModel. 功能基本上有效,但当然,它将自身附加到每个模型类,而不仅仅是MyModel。 So if I have MyModel and MyOtherModel in the same action, it'll assume MyOtherModel has custom_method :first_field, :second_field as well. 因此,如果我在同一个动作中有MyModel和MyOtherModel,它将假设MyOtherModel具有custom_method:first_field,:second_field。

So, my question is: How do I attach a method (eg: def custom_method(*args)) to every class that inherits from ActiveRecord::Base, but not by attaching it to ActiveRecord::Base itself? 所以,我的问题是:如何将一个方法(例如:def custom_method(* args))附加到从ActiveRecord :: Base继承的每个类,而不是将它附加到ActiveRecord :: Base本身?

Any ideas appreciated. 任何想法都赞赏。

=== ===

Edit 编辑

The custom_method is currently attached to ActiveRecord::Base by the following: custom_method当前通过以下方式附加到ActiveRecord :: Base:

module MyCustomModule
  def self.included(base)
    base.extend(self)
  end

  def custom_method(*args)
    # Zippity doo dah - code goes here
  end
end

ActiveRecord::Base.send(:include, MyCustomModule)

Do you know about descendants? 你知道后代吗?

ActiveRecord::Base.descendants

You have to be sure to touch the models before calling it. 在调用之前,您必须确保触摸模型。

See excellent discussion here: 在这里看到很好的讨论

Is there a way to get a collection of all the Models in your Rails app? 有没有办法在Rails应用程序中获取所有模型的集合?

I concur with the commentors above that you may want to consider adding your methods to the meta class, or an intermediary class, or a Module mixin. 我同意上面的评论,你可能想考虑将你的方法添加到元类,中间类或模块mixin。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM