Topic: A simple question, how to use destroy

I have a wedding table, and a photo table, each wedding can have multiple photos.

I have figured out how to add photos to a wedding using a web interface, but cant figure out how to delete them.

I have the following in a file "show.rhtml"

<% for column in Wedding.content_columns %>
<p>
  <b><%= column.human_name %>:</b> <%=h @wedding.send(column.name) %>
</p>
<% end %>

<%= link_to 'Edit', :action => 'edit', :id => @wedding %> |
<%= link_to 'Back', :action => 'list' %>

<% if @wedding.has_photos? %>
  <h3>Photos</h3>
  <table>
  <% for photo in @wedding.photos %>
    <tr>
      <td><%= photo.photo_path %></td>
      <td><%= photo.photo_title %></td>
      <td><%= link_to 'Destroy', { :action => 'delete_photo', :id => @wedding }, :confirm => 'Are you sure?', :post => true %></td>
    </tr>
  <% end %>
  </table>
<% end %>

<%= start_form_tag :action => 'add_photo', :id => @wedding %>
  <p>
    <%=@wedding.id%>
    Photo Title<%= text_field 'photo', 'photo_title', :size => 25 %>
    Photo Path<%= text_field 'photo', 'photo_path', :size => 25 %>
    Thumbnail path<%= text_field 'photo', 'thumbnail_path', :size => 25 %>
  </p>

  <%= submit_tag 'Add!' %>
<%= end_form_tag %>


and i have the following methods in "admin_controller.rb"

  def add_photo
    Wedding.find(params[:id]).photos.create(params[:photo])
    redirect_to :action => 'show', :id => params[:id]
  end
 
  def delete_photo
    Wedding.find(params[:id]).photos.destroy
    redirect_to :action => 'show', :id => params[:id]
  end

unforunately, my delete_photo method does not work, and i get the following error:

wrong number of arguments (0 for 1)

Can anyone help please?

penguin girl

Re: A simple question, how to use destroy

Try sending the photo id in the destroy action and destroying it this way:

# in view
<td><%= link_to 'Destroy', { :action => 'delete_photo', :id => photo }, :confirm => 'Are you sure?', :post => true %></td>

# in controller
def delete_photo
  @photo = Photo.destroy(params[:id])
  redirect_to :action => 'show', :id => @photo.wedding
end

Railscasts - Free Ruby on Rails Screencasts

Re: A simple question, how to use destroy

That worked perfectly, much appreciated. I am not sure i understand it, so will go and study your code now. Many thanks.

Re: A simple question, how to use destroy

what dose the :post => true do? is it post rather then get or is it just a confirmation of the pop up

--

Re: A simple question, how to use destroy

BasicMind wrote:

what dose the :post => true do? is it post rather then get or is it just a confirmation of the pop up

It uses JavaScript to send a POST request instead of a GET request. This is because you never should use GET requests to do something destructive - you don't want it to be triggered by spiders and other automated tools.

BTW, I think :post => true is being depricated in 1.2/edge rails in favor of :method => :post.

Railscasts - Free Ruby on Rails Screencasts