Search code examples
ruby-on-railsruby-on-rails-3nested-attributesdestroy

Remove nested attribute rails


I have a Post model that

has_many photos 

The Post model has

accepts_nested_attributes_for :photos

In my Post edit form i show all the images that are currently associated with the post

<% for photo in @post.photos %>
  <%= image_tag(photo.avatar.url(:thumb)) %> <%= link_to "Remove Photo", post_photo_path(@post, photo), :method => :delete %>
<% end %>

When hovering over over the Remove Photo link the path looks like so

http://localhost:3000/posts/17/photos/45

I get uninitialized constant PhotosController, but that's expected as there isn't one.

My question is do i create one and have a destroy action in there that will just delete that photo.. Is this the way to go about it or is there a better way?

EDIT

Photos Controller

 def destroy
  @photo = Photo.find(params[:id])
  @photo.destroy
  redirect_to edit_post_path, :notice => "Successfully deleted Photo"
 end

Routes

resources :posts do
resources :photos
resources :departments
end

Rake Routes

edit_post GET    /posts/:id/edit(.:format)

Thanks


Solution

  • My opinion is that the best thing to do would be to create a PhotosController to handle the destroy action. That way you will preserve the Single Responsibility Principle, and have less workaround with adding custom routes.

    Also, there is the option to put that one action in the PostsController if you are really sure you won't be adding any additional actions connected to Photos (like tagging photos, or whatever).

    It's really up to you, but i believe the first one is easier.

    If your going with the second option, be sure to create a route for the destroy photo action in the PostsController and the link should be pointing at that exact action.

    Your routes.rb:

    resources :posts do
       resources :photos, :only => [:destroy]
       resources :departments
    end