在Rails中,可以通过以下几种方式从一个控制器访问另一个控制器的方法:
# 源控制器
class SourceController < ApplicationController
def method_in_source
@data = "Hello from source controller!"
redirect_to target_path
end
end
# 目标控制器
class TargetController < ApplicationController
def method_in_target
puts @data # 输出 "Hello from source controller!"
end
end
# 源控制器
class SourceController < ApplicationController
def method_in_source
redirect_to target_path(data: "Hello from source controller!")
end
end
# 目标控制器
class TargetController < ApplicationController
def method_in_target
puts params[:data] # 输出 "Hello from source controller!"
end
end
# 共享模块
module SharedMethods
def shared_method
"Hello from shared method!"
end
end
# 源控制器
class SourceController < ApplicationController
include SharedMethods
def method_in_source
puts shared_method # 输出 "Hello from shared method!"
end
end
# 目标控制器
class TargetController < ApplicationController
include SharedMethods
def method_in_target
puts shared_method # 输出 "Hello from shared method!"
end
end
这些方法可以根据具体的业务需求和代码结构选择适合的方式来实现控制器间的方法访问。
领取专属 10元无门槛券
手把手带您无忧上云