2011-07-29 18 views
2

說我有以下控制器:如何幹起我的控制器操作?

class FooController < ApplicationController 

    def show 
    end 

    def a 
    foo = Foo.find(params[:id]) 
    foo.a 

    redirect_to foo_url(foo) 
    end 

    def b 
    foo = Foo.find(params[:id]) 
    foo.b 

    redirect_to foo_url(foo) 
    end 

    def c 
    foo = Foo.find(params[:id]) 
    foo.c 

    redirect_to foo_url(foo) 
    end 

end 

反正是有得到after_filter進行共享重定向代碼?

+2

http://stackoverflow.com/questions/6181687/why-redirect-to-in-around-filter-or-after-filter-wont-work – sled

+0

你們是不是要找到一種方法來映射Foo公共方法到FooController操作? – Kostas

回答

0

把它留在原地。 after_filters在這種情況下不起作用。

1

這裏是你的代碼重構:

class FooController < ApplicationController 

    before_filter :get_foo, :except => [:show] 

    def show 
    end 

    def a 
    @foo.a 
    redirect_to @foo 
    end 

    def b 
    @foo.b 
    redirect_to @foo 
    end 

    def c 
    @foo.c 
    redirect_to @foo 
    end 

    private 

    def get_foo 
    @foo = Foo.find(params[:id]) 
    end 

end 
+1

我會省略最後一個方法(redirect_to_foo),並在動作 – Kostas

+0

@vrinek - 完成後簡單地將它保留爲'redirect_to @ foo'。 –

+0

是的,我實際上使用了decent_exposure,因此@foo = Foo.find部分不是問題。我只是試圖讓所有這些方法自動重定向,而不必重複代碼。 – patrick

2

試試這個:

class FooController < ApplicationController 

    def show 
    end 

    [:a, :b, :c].each do |name| 
    define_method(name) do 
     foo = Foo.find(params[:id]) 
     foo.send(:name) 
     redirect_to foo_url(foo)  
    end 
    end 
end 
+0

儘管你的回答是正確的,但我發現它不太可能用於真實世界的控制器。假設問題中的例子只是一個普通的電路圖,'define_method'將不會很有用。 – Kostas

+0

如果用戶試圖根據控制器操作在有效負載上執行方法,該解決方案將很好地工作。當您在有效載荷對象上執行上下文操作時(例如,不喜歡,標記,書籤等),此類模式非常常見。 –

2

after_filter不會在這種情況下工作。

我會用下面的方法。

class FooController < ApplicationController 

    before_filter :get_foo, :only => [:a, :b, :c] 

    def show 
    end 

    def a 
    do_and_redirect(:a) 
    end 

    def b 
    do_and_redirect(:b) 
    end 

    def c 
    do_and_redirect(:c) 
    end 

    private 

    def get_foo 
    @foo = Foo.find(params[:id]) 
    end 

    def do_and_redirect(method_name) 
    @foo.send(method_name) 
    redirect_to foo_url(@foo) 
    end 

end 
相關問題