2014-03-02 44 views
0

我有一個應該發送POST請求的Rails應用程序,但由於某些原因正在發送GET。Rails的發送GET請求時,它應該是POST

查看:

<% if @competition.users.exclude?(@user) %> 
    <%= link_to 'Attend Competition', attend_competition_path(@competition.id), :method => :post %> 
<% else %> 
    <%= link_to 'Withdraw', withdraw_competition_path(@competition.id), :method => :post %> 
<% end %> 

控制器:

def attend 
    p current_user.daily 
    @competition = Competition.find(params[:id]) 
    if @competition.users.include?(current_user) 
    flash[:error] = "You're already attending this competition." 
    elsif current_user.daily == [] 
    flash[:error] = "You must have a working device to compete." 
    else 
    current_user.competitions << @competition 
    flash[:success] = "Attending competition!" 
    end 
    redirect_to @competition 
end 

def withdraw 
    p "WITHDRAWING" 
    @competition = Competition.find(params[:id]) 
    p @competition 
    attendee = Attendee.find_by_user_id_and_competition_id(current_user.id, @competition.id) 
    if attendee.blank? 
    flash[:error] = "No current attendees" 
    else 
    attendee.delete 
    flash[:success] = 'You are no longer attending this competition.' 
    end 
    p attendee 
    redirect_to @competition 
end 

路線:

resources :competitions do 
    post 'attend', on: :member 
end 

resources :competitions do 
    member do 
    post 'withdraw' 
    end 
end 

所以我按一下按鈕,轉到頁,卻得到一個錯誤,有沒有GET請求的路由。不應該有獲取請求的路由,但應該發送帖子。

ActionController::RoutingError (No route matches [GET] "/competitions/1/withdraw") 
+0

您的瀏覽器中禁用JavaScript腳本嗎? – usha

+0

從rails文檔link_to:'請注意,如果用戶禁用JavaScript,請求將回退到使用GET' – usha

+0

我需要啓用什麼JavaScript?我有Jquery,但是我需要Jquery-ujs還是Jquery-ui – Marcus

回答

0

一兩件事你可以做的是運行:

rake routes 

會告訴你所有可用的路線和他們的方法。我相信,既然你正在做一個方法的文章,然後創建它不理解你正在嘗試做什麼。我想看看我是否能找到合適的方法來做到這一點,但我確實發現了Rails的文件說:

如果你是依靠職務行爲,你應該在你的控制器的動作檢查它通過使用請求對象的方法進行post?,delete?,:patch或put ?.

因此,您可能需要檢查控制器操作中的帖子。我尋找一個如何做到這一點的例子,但找不到任何東西。在你的路由

來看,它應該工作,你有它的方式。另一個要嘗試的是使用「put」而不是「post」。

,你可能要考慮另外一個選擇是讓一個形式和風格一樣,如果這是你要的樣子鏈接按鈕。

Mike Riley

相關問題