在其他控制器中访问变量的解决方法是使用attr_accessor或attr_writer来定义一个可以读取和写入的实例变量。下面是一个示例代码:
class ApplicationController < ActionController::Base
attr_accessor :my_variable
def some_method
@my_variable = "Hello, world!"
end
end
class OtherController < ApplicationController
def another_method
puts @my_variable
end
end
在上面的示例中,attr_accessor定义了一个名为my_variable的实例变量,并且可以在ApplicationController和其子控制器中进行读取和写入。在some_method方法中,我们将@my_variable设置为字符串"Hello, world!",然后在another_method中使用puts语句打印出@my_variable的值。
这样,就可以在其他控制器中访问和使用my_variable变量了。