覆盖ActiveSupport ::模型关注

时间:2019-02-22 22:20:16

标签: ruby-on-rails activesupport-concern

我有一个担忧,看起来像这样:

module Foo
  extend ActiveSupport::Concern

  def bar
    puts "bar"
  end
end

其他三个模型使用该类方法,因为它们需要相同的东西。然后,我有一个一次性模型,该模型需要该方法执行其他操作。我有这样的设置:

class FooFoo < ApplicationRecord
  def self.bar
    puts "foo bar"
  end
end

现在,当我调用FooFoo.bar时,它将打印“ foo”而不是“ foo bar”。如何覆盖关注中定义的方法?我希望它只运行我的模型FooFoo中定义的方法,而不要运行关注的Foo中的方法。我环顾四周,但我不认为自己需要什么。一些帮助将不胜感激!

编辑:我也尝试过这种方法,希望它能工作,但没有成功

class FooFoo < ApplicationRecord
  def FooFoo.bar # I used FooFoo.bar here instead of self.bar
    puts "foo bar"
  end
end

1 个答案:

答案 0 :(得分:1)

问题在于您需要明确声明希望bar成为类方法...

module Foo
  extend ActiveSupport::Concern

  class_methods do 
    def bar
      puts "bar"
    end
  end
end

现在,您可以覆盖它...

class FooFoo < ApplicationRecord
  def self.bar
    puts "foo bar"
  end
end
相关问题