【发布时间】:2013-09-08 10:04:05
【问题描述】:
我正在使用一个库,该库在数据库中的两个条目之间实现belongs_to 关联。由于这不是我需要的行为,我想通过prepend 覆盖此方法。但是 pry 告诉我原来的方法仍然被调用。我仔细检查了一下,我使用的是 ruby 2.0。
前面的代码:
module Associations
module ClassMethods
[...]
#Add the attributeName to the belongsToAttributes
#and add a field in the list for the IDs
def belongs_to(attr_name)
@belongsToAttributes ||= []
@belongstoAttributes << attr_name
create_attr attr_name.to_s
attribute belongs_to_string.concat(attr_name.to_s).to_sym
end
def belongsToAttributes
@belongsToAttributes
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
# prepend the extension
Couchbase::Model.send(:prepend, Associations)
我在这个课程中使用这个:
注意:我也试过直接覆盖这个类中的方法,但是还是没有发生
require 'couchbase/model'
class AdServeModel < Couchbase::Model
[...]
#I tried to add the belongs_to method like this
#def belongs_to(attr_name)
# @belongsToAttributes ||= []
# @belongstoAttributes << attr_name
# create_attr attr_name.to_s
# attribute belongs_to_string.concat(attr_name.to_s).to_sym
# end
# def belongsToAttributes
# @belongsToAttributes
# end
end
当我使用 pry 检查时,它显示我最终进入了 this 方法调用:
def self.belongs_to(name, options = {})
ref = "#{name}_id"
attribute(ref)
assoc = name.to_s.camelize.constantize
define_method(name) do
assoc.find(self.send(ref))
end
end
任何指向我做错了什么的指针都将不胜感激。
编辑: 好的,我解决了这样的问题:
self.prepended(base)
class << base
prepend ClassMethods
end
end
end
# prepend the extension
Couchbase::Model.send(:prepend, Associations)
由于 Arie Shaw 的帖子包含解决此问题的重要指示,我将接受他的回答。尽管他错过了关于扩展和预先设置我要调用的方法的要点。有关我在添加方法时遇到的麻烦的更详细讨论,请参阅this 问题。
【问题讨论】:
标签: ruby-on-rails ruby couchbase ruby-2.0