如何在rails after_kind hook中调用define_method

时间:2016-12-08 08:41:10

标签: ruby-on-rails activerecord hook

当我在钩子函数中调用define_method时: 发生错误:

undefined method `define_method' for #<Myentity:0x007f9e4eda5928>

这是一个例子:

class EntityInstance < ApplicationRecord

  after_find :define_relation

  def define_relation
    define_method "example" do |x|

    end
  end

end

如何更改hook方法中的上下文或如何在hook方法中使用此函数?

很多!

1 个答案:

答案 0 :(得分:0)

应该在课程的上下文中调用

define_method

含义,取决于您要定义方法的位置(在MyentityMyentity类的实例的单例类中),您应该使用

 def define_relation
   # define method available only to this particular instance of Myentity
   class_eval do
     define_method "example" do |x|
     end
   end
 end

 def define_relation
   # define a method available to all instances of Myentity class
   self.class_eval do
     define_method "example" do |x|
     end
   end
 end