我正在使用 Ruby on Rails。我有一个名为 PatientFactory 的模块,它将包含在 Patient 模型中。
我需要从该模块访问患者的 ID。
module PatientFactory
def self.included(base)
# need to access instance variable here
...
end
end
但更重要的是,我需要在 self.included(base) 我可以在此方法之外轻松访问它,但如何在内部访问它?
最佳答案
假设你想这样做:
class Patient < ActiveRecord::Base
include PatientFactory
end
然后您将像这样访问 id:
module PatientFactory
def get_patient_id
self.id
end
end
a = Patient.new
a.id #=> nil
a.save
a.id #=> Integer
当你的模块被包含在一个类中时,它的所有方法都成为该类的实例方法。如果您更愿意扩展它们,它们会被插入到您类的单例类中,因此它们可以像类方法一样访问。
关于ruby-on-rails - RoR,从模块调用列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12959873/