2011-04-19 149 views
0

我有一個配置文件,這個配置文件有很多curso s(課程)。我顯示了此配置文件的show.html.erb配置文件中的所有課程。刪除嵌套對象

<% for curso in @profile.cursos %> 
<li><%=h curso.nome %> - <%=h curso.universidade %><br> 
Ingresso em: <%=h curso.ano_ingresso %> - Encerra em: <%=h curso.ano_termino %> 
<li> 
<%= button_to 'Delete', { :action => "destroy", :id => curso.id },:confirm => "Are you sure?", :method => :delete %> 

這種方式,我能夠顯示所有配置文件有它的頁面上的課程,但button_to delete是行不通的。我已經嘗試了很多東西,但我覺得我迷路了。關於如何創建鏈接或按鈕或刪除課程的任何想法?

回答

4

在你的路由文件

resources :profiles do 
    resources :courses 
end 

然後,你可以使用的link_to方法

<%= link_to "Delete", profile_course_path(profile, course), :method => :delete %> 

請確保您提供正確的變量profilecourse

然後在你的courses_controller.rb你需要獲取配置文件。

before_filter :get_profile 

def get_profile 
    @profile = Profile.find(params[:profile_id]) if params[:profile_id] 
end 

def destroy 
    @course = Corse.find(params[:id]) 
    @course.destroy 
    redirect_to profile_courses_path(@profile) 
end 

這將帶你回到正確的配置文件URL與它的嵌套課程。

更新

對於您可以使用下面的鏈接新課程:

<%= link_to "New Course", new_profile_course_path(profile) %> 

這將需要你在課程控制器new行動。您應該閱讀嵌套表格here

+0

Thansk爲答案! 我想這會起作用,但是現在當我點擊刪除鏈接時,它會指引我創建一個新課程。我不知道這是因爲我有我的路'匹配「/型材/:id_profile/cursos」:以=>「cursos#new'',但沒有這場比賽,我不能創造任何新的課程。任何想法? – Luk 2011-04-19 23:59:38

+0

只需使用我設置的路線。刪除該路線並使用新課程檢查代碼是否有更新。你想使用嵌套鏈接。 – s84 2011-04-20 01:36:22

+0

謝謝,現在我可以創建課程,並且我正在變得更好。 對鏈接進行了一些更改 '<= = link_to「刪除」,profile_curso_path(@profile,curso),:method =>:delete%> 它現在引導我使用cursos /:curso_id鏈接,但是說沒有路線。我手動添加了一條消滅比賽的路線,並且它很有效,但按照你所說的,這是「錯誤的」。任何意識如何我可以解決? – Luk 2011-04-20 05:57:14