2010-03-05 73 views
0

我不知道我是否正確執行此操作。我有一個操作,我想要複製,創建,並保存一個新的對象,如果用戶登錄,或者重定向,如果他們沒有登錄。我不在這裏使用一個表單,因爲我正在使用一個風格化的按鈕,圖像,看起來像這樣:更新或重定向的Rails路由

<a href="/lists/add/<%= @list.id %>" class="button"> 
    <span class="add_list">Learn these words</span> 
</a> 

和行動看起來是這樣的:

def add  
    if is_logged_in? 
     list = logged_in_user.copy_list(params[:id]) 
     if list.save 
     flash[:notice] = "This list is now in your stash." 
     redirect_to stash_zoom_nav_quiz_path(list, "zoomout", "new", "quizoff") 
     else 
     flash[:notice] = "There was a problem adding this list." 
     redirect_to :back 
     end 
    else 
     redirect_to :controller => "users", :action => "signup_and_login", :list_id => params[:id]  
    end 
    end 

map.resources :lists, :collection => {:share => :get, :share_callback => :get, :add => :put} 

我已經加入這種動作爲:把我的路線,我不知道這是否是正確的或如果其他東西是正確的方式,甚至可以做到這一點。任何幫助表示讚賞。

回答

2

具體回答你的問題是

map.resources :lists, :collection => { :share => :get, :share_callback => :get }, :member => { :add => :put } 

add行動工作的部件,而不是一個集合。

但你的代碼還有其他問題。首先,你應該總是使用Rails助手來生成URL。其實路徑/lists/add/<%= @list.id %>是錯誤的。它應該是/lists/<%= @list.id %>/add

變化

<a href="/lists/add/<%= @list.id %>" class="button"> 
    <span class="add_list">Learn these words</span> 
</a> 

<% link_to add_list_path(@list), :class => "button" do %> 
    <span class="add_list">Learn these words</span> 
<% end %> 

控制器可以簡化。在前過濾器中移動is_logged_in?檢查。

class MyController < ActionController::Base 

    before_filter :require_logged_user, :only => %w(add) 

    def add  
    list = logged_in_user.copy_list(params[:id]) 
    if list.save 
     flash[:notice] = "This list is now in your stash." 
     redirect_to stash_zoom_nav_quiz_path(list, "zoomout", "new", "quizoff") 
    else 
     flash[:notice] = "There was a problem adding this list." 
     redirect_to :back 
    end 
    end 

    protected 

    def require_logged_user 
    if !is_logged_in? 
     redirect_to :controller => "users", :action => "signup_and_login", :list_id => params[:id] 
    end 
    end 

end 
+0

只是出於好奇,會錯誤標記成員作爲集合的負面影響是什麼? – TenJack 2010-03-09 05:44:14

+0

也謝謝你的幫助,我不知道你可以用link_to創建一個塊! – TenJack 2010-03-09 05:56:09

+0

有一件事,我想我應該在這裏使用POST方法b/c我創建一個新記錄,但是,如果我使用POST或PUT,我會得到一個「ActionController :: UnknownAction」路由錯誤。看來GET是單詞的唯一方法,這可以嗎? – TenJack 2010-03-09 06:19:35

0

試試這個在您的routes.rb:

map.resources :lists, :member => {:add => :put}, :collection => {:share => :get, :share_callback => :get} 

:成員 - 同:集合,但對於特定成員上進行操作的行爲。