【问题标题】:Rails has_many overridden by an included moduleRails has_many 被包含的模块覆盖
【发布时间】:2011-07-09 06:50:25
【问题描述】:

我有一个看起来像这样的模型,#friends 方法覆盖了关联生成的方法#friends:

class User < ActiveRecord::Base
  has_many :friends
  def friends
    puts 'hi'
  end
end

但是当我将代码重构为如下所示时,关联生成的方法#friends 不会被包含的好友模块覆盖:

module User
  module Friends
    def friends
      puts 'hi'
    end
  end
end

require 'user/friends'
class User < ActiveRecord::Base
  has_many :friends
  include User::Friends
end

为什么关联生成的#friends 不会被包含的 User::Friends#friends 方法覆盖?

【问题讨论】:

  • 无论如何,覆盖 ActiveRecord 关联可能不是一个好主意。可能会导致一些问题。

标签: ruby-on-rails ruby include


【解决方案1】:

Ruby 的方法查找从当前类开始,如果找不到匹配项,则查找包含的模块和超类(IIRC,它查找元类,然后是模块,然后是超类,然后是超类元类等)。因此,当您在类中定义方法时,您是在覆盖,但是当您在模块中定义方法时,它不会被查找。

为了覆盖该方法,您应该在模块内部使用undef :friendsalias :old_friends :friends(以便原始方法仍然可用)。最好在模块的 self.included 方法中执行此操作

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多