2012-04-27 19 views
0

我有User型號和Account控制器。當用戶訪問網址/account時,它應該顯示一個表單,其中包含一個帶有用戶名的文本字段和一個用於提交表單的按鈕。我的路線中有match '/account' => 'account#index'檢測是否顯示或處理基於GET或POST的表格

以我控制器我有限定的本方法:

def index 
    @user = User.find(session[:user_id]) 
end 

(檢查用戶認證在before_filter發生)

現在的形式正確地顯示,並且甚至正確填充。但是,我需要知道如何判斷表單是否已提交。什麼是導軌方式?我是否有單獨的路線來注意POST請求/account?或者我在index方法中檢測請求類型?我在什麼時候決定表格是否已提交?

回答

1

您可以檢測表單是否已在索引控制器內部提交。我相信params hash gets會爲請求使用的方法設置key:方法。

另一種方法是重做您的路線。取而代之的match '/account' => 'account#index'你可以這樣做:

get '/account' => 'account#index' 
post '/account' => 'account#post_action' 

然後你的控制器內,你可以這樣做:

def index 
    @user = User.find session[user_id] 
end 

def post_action 
    @user = User.find session[user_id] 
    if @user.update_attributes params[:user] 
    flash[:notice] = 'Update Successful' 
    render :action => index 
    else 
    flash[:notice] = 'Update Unsuccessful' 
    render :action => index 
    end 
end