2015-05-04 57 views
0

我遇到了PATCH請求的問題。Rails使用PATCH請求渲染或redirect_to

我想PATCH "/activities/7/mans"update一些價值
但如果更新值無效,那麼我怎麼會重定向到:new

這裏的鐵軌服務器日誌

Started PATCH "/activities/7/mans" for 127.0.0.1 at 2015-05-04 12:55:58 +0800 
Processing by MansController#new as HTML 
Parameters: {"utf8"=>"✓","authenticity_token"=>"Qnn/N9yWMtxAwA9N+br5r+mMvPdoY4fBJaI3sCYnObY=","activity_id"=>"7"} 

當我使用更新
我總是得到{GET} not {PATCH}

Started GET "/activities/7/mans" for 127.0.0.1 at 2015-05-04 12:58:56 +0800 
Processing by MansController#show as HTML 
Parameters: {"activity_id"=>"7"} 

這裏後呈現新的route.rb設置

resources :activities do 
    resources :mans, :only => [:index ,:create] do 
    collection do 
     patch :new 
    end 
    end 
end 

這裏是我的控制器操作

def new 
    @activity = Activity.find_by_id(params[:activity_id]) 
    @man= Man.new 
    end 

    def create 
    @man = Man.new(man_params) 
    if @man.age <20 
     redirect_to :new 
    end 
    end 
+1

你能告訴你的控制器行動?這很可能與您如何進行重定向有關。 – jphager2

回答

0

當有它的共同不是重定向,但與一些HTML的響應一次驗證錯誤:

def create 
    @man = Man.new(man_params) 
    if @man.save # validation for age < 20 should be in the model 
     redirect_to my_redirect_path 
    else 
     render :new 
    end 
    end 

完全一樣爲update行動,你沒有在這個問題提供:

def update 
    @man = Man.find(man_params[:id]) 
    if @man.update_attributes(man_params) # validation for age < 20 should be in the model 
     redirect_to my_redirect_path 
    else 
     render :edit 
    end 
    end 

這樣你就可以打印使用@man.errors視圖中的任何驗證錯誤。

爲了這個工作,你應該有edit(當然update)控制器動作,並修改路線如下(如果你不需要showdestroy動作):

resources :activities do 
    resources :mans, :except => [:show, :destroy] 
end