2011-11-27 68 views
0

我是Rails的新手,目前使用Rails 3,請耐心等待。我有一個基本的應用程序,基本的腳手架控制器/模型,例如聯繫人。在rails 3中定義一個方法的路由

顯示/編輯等方法之一。我已經添加了一個名爲newcontacts(我也添加了newcontacts.html.erb),這將最終顯示導入的最後5個聯繫人,但此刻我是使用相同的碼的一個會發現在一個控制器的基本索引方法(ⅰ打算以過濾在稍後的點的數據),在控制器中的方法是 -

def newcontacts 

    @contacts = Contact.all 

    respond_to do |format| 
    format.html # index.html.erb 
    end 
end 

我可以訪問本地主機:3000 /接觸它顯示來自聯繫人控制器的索引方法動作,但是當我嘗試使用localhost:3000/contacts/newcontacts訪問此方法(newcontacts)時,它返回錯誤

Couldn't find Contact with id=newcontacts 

我已經看過了的routes.rb文件,因爲我相信這是什麼需要編輯,添加以下行的routes.rb

match 'newcontacts', :to => 'contacts#newcontacts' 

但是當我把這個作品只本地主機:3000/newcontacts。

所以我的問題是,我如何獲得url localhost:3000/contacts/newcontacts的工作?

任何幫助將是偉大的。

回答

1

認爲你想要做的是add another RESTful action

resources :contacts do 
    # This will map to /contacts/newcontacts 
    get 'newcontacts', :on => :collection # Or (not and; use only one of these)... 

    # This will map to /contacts/:id/newcontacts 
    get 'newcontacts', :on => :member  # ... if you want to pass in a contact id. 
end 
+0

感謝您的快速回復。當我去/ contacts/newcontacts時,它現在顯示'沒有路由匹配[GET]「/ contacts/newcontacts」' – norbert

+0

@AndyN你是否刪除了其他匹配路由?有沒有'link_to'或模板中的東西? –

+0

匹配'newcontacts',:to =>'contacts#newcontacts'仍然需要嗎?我目前正在獲取錯誤config/routes.rb:8:語法錯誤,意外的kEND,期待$ end(SyntaxError)與它在? – norbert

0

在你的routes.rb文件試試這個:

resources :contacts do 
    member do 
    put 'newcontacts' 
    end 
end 

這將在觸點控制新動作添加。

+0

這實際上是'/ contacts /:id/newcontacts'。這可能是想要的;我不確定。 –

+0

是的 - 現在我已經看到你的答案我懷疑你已經比我更好地掌握了需求:) – Nick