Deleting nested objects

跟風遠走 提交于 2020-01-06 14:01:17

问题


I have a profile, and this profile has many cursos (courses). I show all the courses a profile has on the show.html.erb of this profile.

<% 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 %>

This way, I'm able to show all the courses a profile has on it's page, but the button_to delete just doesn't work. I have tried many things already, but I think I'm lost. Any idea on how I can create a link or a button or anything to delete the courses?


回答1:


In your routes file

resources :profiles do
    resources :courses
end

Then you can just use link_to method

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

Make sure you are providing the correct variables profile and course

Then in your courses_controller.rb you need to get the profile.

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 

That will take you back to the correct profile url with it's nested courses.

update

For new courses you can use the following link:

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

That will take you to the new action in the courses controller.

You should read up on nested forms here.



来源:https://stackoverflow.com/questions/5710642/deleting-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!