2015-12-07 36 views
3

我正在爲一個類的網站,我試圖實現一個名爲'用戶'的模型和稱爲'關係'的連接模型的朋友請求函數。我在用戶#顯示頁面上有一個按鈕,應該使用關係控制器中的create方法添加好友。下面是按鈕的代碼:rails link_to使用獲取而不是後

<%= link_to "Add as Friend", relationships_path(:friend_id => @user), method: :post %> 

當我按下鏈接,但是,它會嘗試訪問索引方法來代替。查看控制檯後,它看起來像鏈接正在發送GET請求,該請求將路由到索引方法,而不是發送到創建方法的POST請求。有人可以解釋爲什麼這個錯誤正在發生,我該如何解決它?

編輯:按照要求,這裏是我在我的路線:

Rails.application.routes.draw do 
    resources :interests 
    get 'interests/create' 

    get 'interests/destroy' 

    get 'home/index' 

    get 'sessions/create' 

    get 'sessions/destroy' 

    resources :users 
    resources :relationships 
    resources :subscriptions 

    # The priority is based upon order of creation: first created -> highest priority. 
    # See how all your routes lay out with "rake routes". 

    # You can have the root of your site routed with "root" 
    # root 'welcome#index' 
    root 'home#index' 
    get "/auth/:provider/callback" => "sessions#create" 
    get "/signout" => "sessions#destroy", :as => :signout 
+0

您是否在routes.rb中添加了此路徑?我認爲你嘗試訪問的鏈接是:**/relationships /:friend_id ** – sahil

+1

請發佈您的routes.rb文件 –

+0

我已經添加了我的路由文件中的內容。 –

回答

0

我敢肯定你是匹配了錯誤的路線。運行耙路線並查看鏈接到Relationships#create的路線。

+0

下面是運行耙路線時出現的情況:關係GET /relationships(.:format)relationships#index POST /relationships((::format)relationships#create –

+0

這很奇怪,如果您嘗試使用它,會發生什麼情況? <%= button_to「Add as Friend」,relationships_path(friend:@user)%> 或者如果你寫了一個新的路線,像'test',發給''relationships#create'(你不應該這樣做,爲測試目的) – alebian

+0

我拿出你說的方法。同樣的錯誤。 –

6

使用link_to幫助者向Rails表明您希望在您的HTML中生成a標記。 HTML specification regarding a tags中沒有元素允許生成POST請求。因爲Rails理解允許使用鏈接發出請求POSTDELETE的實用程序,但它會在link_to幫助程序中提供這些選項。然而,它的實現必須在引擎蓋下使用JavaScript才能正常運行。

檢查jquery-ujs is installed,並確認您的資產管道工作正常,以此方式使用助手。

您也可以評估是否使用form_forbutton更好,因爲那會自動POST

+0

jquery-ujs在我的gemfile中,並且已安裝。我不確定如何使用我的資產管道。我也嘗試使用按鈕,但我得到了同樣的錯誤。 –

+0

@ B.Allred這將有助於查看您點擊的頁面的完整HTML,並在瀏覽器中爲頁面調出JavaScript控制檯,並查看是否存在任何錯誤。 –

+0

我已經得到它現在的工作。按照教師的建議,我將按鈕的代碼更改爲:\t <%= button_to「subscribe」,{action:'create',controller:'subscriptions',interest_id:@ interest.id}%> \t。感謝您的建議! –

相關問題