修改 ActiveRecord 模块以适用于任何模型
因此,不久前,我创建了一个小模块来充当可投票多态关联所需的方法,虽然它最初仅用于 ActiveRecord,但我现在想将它与 mongo 一起使用,因为我使用的是 mongoid我需要在这个实例中创建的关联的所有方法都具有相同的名称,这里的所有内容都可以看一下我以前的代码:
# config/initializers/acts_as_votable.rb
module ActsAsVotable
end
module ActiveRecord
class Base
class << self
cattr_accessor :votable
def acts_as_votable
has_many :votes, :as => :voteable
end
def acts_as_voter
has_many :votes, :as => :voter
end
def votable?
method_defined? :votes
end
end
def votable?
self.class.send(:method_defined?, :votes)
end
end
end
这是它的使用方式:
class Recipe < ActiveRecord::Base
acts_as_votable
# more stuff...
end
所以你会注意到这里有两个问题,首先,我'米延伸ActiveRecord::Base
,我如何才能使其适用于任何模型,而不仅仅是继承自 ActiveRecord
的模型?,其次,我是否真的需要一个像这样的空模块 ActsAsVotable
之一?我在这里做错了什么?
如果我只是将所有代码放入模块 ActsAsVotable
中,我是否应该能够从我的模型中调用 includes ActsAsVotable
?
So a while ago I created a small module to serve as the methods I need for a votable polymorphic association, and while it was originally meant to be used only for ActiveRecord I now want to use it with mongo, and since I'm using mongoid all of the methods for the associations I need to create in this intance have the same names and everthing here take a look at my previous code:
# config/initializers/acts_as_votable.rb
module ActsAsVotable
end
module ActiveRecord
class Base
class << self
cattr_accessor :votable
def acts_as_votable
has_many :votes, :as => :voteable
end
def acts_as_voter
has_many :votes, :as => :voter
end
def votable?
method_defined? :votes
end
end
def votable?
self.class.send(:method_defined?, :votes)
end
end
end
And here is how it was used:
class Recipe < ActiveRecord::Base
acts_as_votable
# more stuff...
end
So you'll notice two issues here, firstly, I'm extending ActiveRecord::Base
, how can I make this work for any model, not just ones that inherit from ActiveRecord
?, Secondly do I actually need an empty module like that ActsAsVotable
one? What am I doing wrong here?
If I just put all that code into the module ActsAsVotable
, shouldn't I just be able to call includes ActsAsVotable
from my model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,将其放入初始值设定项或
/lib
中,但确保该路径已加载到您的应用程序中。然后在任何模型中:
最后:
First, put this in an initializer or in
/lib
but be sure the path is loaded in your application.Then in any model:
Finally: