删除嵌套对象 [英] Deleting nested objects
问题描述
我有一个个人资料,并且此个人资料有很多curso
(课程).我会在个人资料的show.html.erb
上显示该个人资料中的所有课程.
I have a profile, and this profile has many curso
s (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 %>
这样,我可以在个人资料页面上显示其个人资料中的所有课程,但是button_to 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?
推荐答案
在您的路线文件中
resources :profiles do
resources :courses
end
然后您可以只使用link_to方法
Then you can just use link_to method
<%= link_to "Delete", profile_course_path(profile, course), :method => :delete %>
确保提供正确的变量profile
和course
Make sure you are providing the correct variables profile
and course
然后,您需要在courses_controller.rb中获取配置文件.
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.
对于新课程,您可以使用以下链接:
For new courses you can use the following link:
<%= link_to "New Course", new_profile_course_path(profile) %>
这将带您进入课程控制器中的new
操作.
That will take you to the new
action in the courses controller.
您应该在此处上阅读嵌套表格.
You should read up on nested forms here.
这篇关于删除嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!