2012-12-13 46 views
3

是否有必要在控制器中提及控制器中的私有方法爲helper_methods? 像Rails 3控制器作爲輔助方法的私有方法

class PostsController < ApplicationController 
    helper_method :check_something 

    def new 
    check_something 
    @post = Post.new 
    end 

    def show 
    @post = Post.find(params[:id]) 
    end 

private 

    def check_something 
    redirect_to(root_path) and return if something 
    end 
end 

是語句:需要helper_method :check_something?如果是的話爲什麼

而當我從控制器調用私人方法的行動方法是params散列訪問私人或helper方法?

+0

你可以拿出輔助方法的東西。我很確定你必須將它作爲參數傳遞給'check_something'方法。另外,這看起來應該是'before_filter' – varatis

回答

5

不,這是沒有必要的。您可以隨時在您的控制器內撥打private控制器的方法。

而且,params將自動適用於控制器內的private方法。

3

無需在控制器中提及私有方法作爲輔助方法。您可以通過傳遞像params這樣的參數或任何東西來直接從同一個控制器的其他方法調用它們。

class ContorllerName < ApplicationController 
def index 
    private_method(params) 
end 
private 
def private_method(vals) 
    vals 
end 
end 
7

我想你誤解了'helper_method'的概念。

helper_method是用來使你的控制器方法作爲其方法在你的助手模塊

所以你的控制器裏面,你可以隨時訪問您的私有方法沒有「helper_method」部分

和如果您添加一個控制器方法作爲輔助方法,因爲你已經做了,在你看來,你可以簡單地把它

,併爲你的第二個問題,是PARAMS哈希是通過控制器的私有方法訪問

HTH