2013-11-22 19 views
0
class UsersController < ApplicationController 
    def create 
    # call the action do_something from ImagesController 
    # continue in the normal flow 
    end 
end 

class ImagesController < ApplicationController 
    def do_something 
    ... 
    end 
end 

執行從另一個控制器的操作我想從UsersController呼叫在ImagesController行動do_something但執行後,我想繼續的create行動,很少正常流動問題:如何在不離開當前控制器

  • 這是不好的做法?
  • 我該怎麼做?我是否必須創建ImagesController的實例,然後調用該操作還是有其他方法?
+1

是的,這是一個不好的做法。你應該找到另一種方式。 –

回答

2

你可以在技術上創建另一個控制器的實例並調用其中的方法,但它很單調乏味,容易出錯並且極不推薦。

如果該功能對於兩個控制器都是通用的,那麼您應該在ApplicationController或創建的另一個超類控制器中使用它。

class ApplicationController < ActionController::Base 
    def common_to_all_controllers 
    # some code 
    end 
end 

class SuperController < ApplicationController 
    def common_to_some_controllers 
    # some other code 
    end 
end 

class MyController < SuperController 
    # has access to common_to_all_controllers and common_to_some_controllers 
end 

class MyOtherController < ApplicationController 
    # has access to common_to_all_controllers only 
end 

另一種方法是

# lib/common_stuff.rb 
module CommonStuff 
    def common_thing 
    # code 
    end 
end 



# app/controllers/my_controller.rb 
require 'common_stuff' 
class MyController < ApplicationController 
    include CommonStuff 
    # has access to common_thing 
end 

源 - Calling a method from another controller

0

這是可能的實際。並不那麼難。

這就是說。這是不好的做法。非常不好的做法。

你想要做的是將你要在控制器中執行的邏輯提取到服務對象中,或將其移入模型中。另外你也可以讓你的第一個控制器繼承你正在嘗試調用的控制器。

那麼,如何調用控制器?

TheController.new.dispatch(:index, request)

+0

我必須在請求參數中放入什麼?如果需要的話可以傳遞給對象? – zer0uno

+0

請求應該與通常在控制器中獲取的請求對象具有相同的類型:ActionController :: Request。 –

相關問題