Rails 新项目遇到一个小问题 大牛来讲解下

themorecolor · October 24, 2014 · Last by themorecolor replied at October 24, 2014 · 1824 hits

先上代码

在 modue A 下

#a/application.rb
module A
  class ApplicationController < ::ApplicationController

    def say_hello
      "hello AAA"
    end

  end
end

#a/welcome_controller.rb
module A
  class WelcomeController < ApplicationController

    def index
      render :text => say_hello
    end

  end
end

在 module B 下

#b/application.rb
module B
  class ApplicationController < ::ApplicationController

    def say_hello
      "hello BBB"
    end

  end
end

#b/welcome_controller.rb
module B
  class WelcomeController < ApplicationController

    def index
      render :text => say_hello
    end

  end
end

每次重新启动后,如果第一次请求是请求 module A 下的,则后面 module A 下的所有请求都没有问题,但是请求 module B 下 则会报错 undefined local variable or method `say_hello'

如果第一次请求是 Module B 下的 然后下面请求 module A 下的会报错 undefined local variable or method `say_hello'

后来在 两个 module 各个 controller 继承的 ApplicationController 前加上 module 名解决

module A
  class WelcomeController < A::ApplicationController
  end
end

module B
  class WelcomeController < B::ApplicationController
  end
end

求详解

我仅仅是猜测下哦。

影响的缘故:

  1. Ruby 的 constant lookup
  2. Rails 的 autoload

我猜你是在 development 环境下

You need to Sign in before reply, if you don't have an account, please Sign up first.