在没有 HTTP 重定向的情况下从另一个控制器操作运行一个控制器操作的正确方法是什么? [英] What's the correct way to run one controller action from another controller action without an HTTP redirect?

查看:22
本文介绍了在没有 HTTP 重定向的情况下从另一个控制器操作运行一个控制器操作的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够根据查询参数和数据库中数据的组合,有条件地从一个控制器操作分派到另一个控制器操作.

I'd like to be able to dispatch from one controller action to another conditionally, based on a combination of query parameters and data in the database.

我现在拥有的是这样的:

What I have right now is something like:

class OldController < ApplicationController
  def old_controller_action
    if should_use_new_controller
      new_params = params.dup
      new_params[:controller] = "new_controller_action"
      redirect_to new_params
      return
    end
    # rest of old and busted
  end
end

class NewController < ApplicationController
  def new_controller_action
    # new hotness
  end
end

这工作得很好,但它发出 HTTP 重定向,这很慢.我希望能够在同一个 HTTP 请求中做同样的事情.

This works just fine, but it issues an HTTP redirect, which is slow. I'd like to be able to do this same thing, but within the same HTTP request.

有没有干净的方法来做到这一点?

Is there a clean way to do this?

赏金将授予可以向我展示一种干净的方法来做到这一点的人,使控制器及其操作相对不变(除了重定向代码本身).

The bounty will go to someone who can show me a clean way to do this that leaves the controllers and their actions relatively untouched (other than the redirect code itself).

推荐答案

不要跨操作调用代码,而是将代码提取到 lib/或其他地方,然后从两个控制器调用该代码.

Instead of calling code across actions, extract the code to lib/ or something, and call that code from both controllers.

# lib/foo.rb
module Foo
  def self.bar
  # ...
  end
end

# posts_controller
def index
  Foo.bar
end

# things_controller
def index
  Foo.bar
end

这篇关于在没有 HTTP 重定向的情况下从另一个控制器操作运行一个控制器操作的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆