2012-07-21 96 views
0

我是Rails新手,並且在此question上遵循了相應的答案。Rails:使用帶按鈕的ajax時發生路由錯誤

這是怎麼回事兒在我的項目:

控制器:

def create 
    def create 
     current_user.likes.create(:post_id => params[:post_id]) 
     render :layout => false 
    end 
end 

.js文件:

$ -> 
    $(".like").click -> 
     post_id = $(this).attr('id') 
     $.ajax 
      type: 'POST' 
      url: 'likes/' + post_id 
      success: -> 
       alert "succsess!" 

的routes.rb

Sample::Application.routes.draw do 
    resources :likes 

    resources :users 
    resources :sessions, only: [:new, :create, :destroy] 
    resources :posts, only: [:create, :destroy] 

    root    to: 'pages#home' 
    match '/about', to: 'pages#about' 
    match '/contact', to: 'pages#contact' 
    match '/help', to: 'pages#help' 
    match '/signup', to: 'users#new' 
    match '/signin', to: 'sessions#new' 
    match '/signout', to: 'sessions#destroy' 
    post '/likes/4', to: 'likes#create', :as => :like 
end 

(我用'/像/ 4'測試提出(它會我將來會'post_id'))。

當我點擊視圖的Like按鈕,等等獲取存儲在數據庫中,但我得到這個錯誤(當我看着在Chrome檢查控制檯)...

POST http://0.0.0.0:3000/likes/4 500 (Internal Server Error) 

......我從來沒有從ajax那裏獲得succsess警報。

當我運行wget --post-data='' http://localhost:3000/likes/4,我得到:

--2012-07-22 19:35:01-- http://localhost:3000/likes/4 
Resolving localhost... ::1, 127.0.0.1, fe80::1 
Connecting to localhost|::1|:3000... failed: Connection refused. 
Connecting to localhost|127.0.0.1|:3000... connected. 
HTTP request sent, awaiting response... 500 Internal Server Error 
2012-07-22 19:35:02 ERROR 500: Internal Server Error. 

任何人都知道是什麼讓這個錯誤?

回答

0

好的,我發現了問題!

首先,感謝Dougui提出的一些很好的觀點,幫助我一路走來!

解決方案:

我不得不唯一性驗證的改變:

validates :tag, :uniqueness => {:scope => :post} 

到:

validates :tag_id, :uniqueness => {:scope => :post_id} 

你可能想知道爲什麼?在此解釋:http://thetenelements.blogspot.no/2011/08/undefined-method-text-for-nilnilclass.html

因此,這裏是我的文件時一切正常:

like.rb

validates :user_id, :uniqueness => {:scope => :post_id} 
    belongs_to :user 
    belongs_to :post 

likes_controller.rb

def userLikePost 
    current_user.likes.create(:post_id => params[:post_id]) 
end 

路線.rb

match '/likes/:post_id', to: 'likes#userLikePost' 

pages.js。咖啡

$ -> 
    $(".like.btn.btn-mini").click (e) -> 
     if $(this).attr("class") == "like btn btn-mini" 
      post_id = $(this).attr('id') 
      $.post '/likes/' + post_id 
     e.stopImmediatePropagation(); 
     $(this).addClass("active") 

HTML按鈕

<button class="like btn btn-mini" id="<%= feed_item.id %>"><i class="icon-heart"></i></button> 

而且在用戶和後模型我有has_many: likes

希望這可以幫助別人:)

0

我認爲這是因爲你做了一個帖子,你的路線是一個get。您可以在錄製命令rake routes時顯示它。嘗試將您的ajax請求類型更改爲GET或更改您的路由。用post代替match

+0

感謝Dougui!它在.js文件中將'GET'替換爲'POST'時有效,但我需要用ajax請求發送一些信息(然後我需要使用POST,對嗎?)。但是當我在routes.rb中用'post'替換'match'時它不起作用。任何消化? – 123ndy 2012-07-21 23:19:40

+0

我的意思是用.js文件中的'GET'取代'POST' – 123ndy 2012-07-21 23:26:18

+0

我想你也可以用GET發送一些信息。你能發送你的'rake routes'命令的結果嗎? – Dougui 2012-07-21 23:38:59