开发者

Deleting nested objects

开发者 https://www.devze.com 2023-02-27 02:32 出处:网络
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.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消