2012-03-10 85 views
1

我試圖在顯示鏈接列表的我的rails應用程序的前端有一個按鈕。我希望他們能夠點擊「添加到收藏夾」如何讓這個POST在rails中工作?

現在我正在努力使它在沒有AJAX的情況下工作,但最終我要添加一次,我得到的後備工作(只是一個然後在js中使用return false;然後使用ajax)

現在,我沒有看到任何錯誤,但它沒有添加最喜歡的時候,我點擊它。任何幫助,將不勝感激

路線:

root :to => 'home#index' 

    resources :resources, :except => [:index] 
    resources :profiles, :only => [:show] 
    resources :favorites, :only => [:create, :destroy] 

    match '/learn', :to => 'pages#learn' 
    match '/contact', :to => 'pages#contact' 
    match '/requests', :to => 'pages#requests' 

收藏控制器

class FavoritesController < ApplicationController 

    before_filter :authenticate_user! 

    def create 
    @favorite = Favorite.new(:resource_id => params[:id], :user_id => current_user.id) 
    if @favorite.valid? 
     @favorite.save 
    else 
     redirect_to root_url 
    end 
    end 

    def destroy 
    # also must find by user as well... 
    @favorite = Favorite.find_by_resource_id(params[:id]) 
    @favorite.destroy 
    redirect_to root_url 
    end 

end 

繼承人我的看法代碼,實際上顯示了 '添加到收藏夾' 鏈接:

<%= link_to favorites_path(resource), :method => :post, :class => "btn btn-warning btn-mini" do %> 
    <i class="icon-star icon-white" rel="tooltip" title="add to favorites"></i> Add to favorites 
<% end %> 

當我將鼠標懸停在網站上,網址顯示爲site.com/favorites.3 ---不確定這是否正確?

+0

什麼,當你點擊鏈接在服務器端會發生什麼?你是否從控制檯的請求中獲得輸出? – 2012-03-10 05:10:16

+0

即時通訊不知道我該怎麼做? – Tallboy 2012-03-10 05:11:13

+0

如果你還不知道,你應該檢查https://github.com/seyhunak/twitter-bootstrap-rails。 :)這是一個很好的引導的寶石 – 2012-03-10 05:20:47

回答

1

默認情況下創建行動後在軌因此而數據比改變默認行爲添加新的行動爲您的目的。

內航線

resources :favorites, :only => [:destroy] do 
get :add, :on => :collection 
end 

視圖*

<%= link_to add_favorites_path(:id => resource), :class => "btn btn-warning btn-mini" do %> 
    <i class="icon-star icon-white" rel="tooltip" title="add to favorites"></i> Add to favorites 
<% end %> 

控制器create行動將得到renamedadd

+0

我想我還是很困惑。如果我不想重命名一個動作,我還會這樣做嗎?我想如果它的ajax調用來創建一個'最喜歡的'它將FavoritesController#創建 – Tallboy 2012-03-10 19:54:05

+0

你能解釋這是做什麼? add_favorites_path(:id =>資源)..它的工作,我不知道爲什麼:/我也不知道這是得到:add,:on =>:collection。我真的很感謝你的幫助'! – Tallboy 2012-03-11 04:14:36

+0

我們爲URL定義了獲取路線「/favourites/add"..for更多信息只需通過guides.rubyonrails.org/routing.html – 2012-03-11 05:36:11

1

我認爲你可以做到這一點使用表來發表,而不是一個鏈接,讓GET或添加這條路線應該讓以及

match "/favorites/add/:id" => "favorites#create" 
+0

我告訴它在link_to中發佈(請參閱最後一段代碼)。該路由已經期待POST,因爲我使用了資源:收藏夾 – Tallboy 2012-03-10 05:20:22

+0

好的,我認爲它的favorites_path(資源)問題,因爲它接合你傳遞資源作爲收藏,所以它試圖獲得與該資源ID的最愛。 – 2012-03-10 05:49:10