How to Create a Delete Link for a Related Object in Ruby on Rails

How to create a delete link for a related object in Ruby on Rails?

<%= link_to 'Destroy', post_comment_path(@post, comment),
data: {:confirm => 'Are you sure?'}, :method => :delete %>

in comments controller:

  def destroy
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
@comment.destroy

respond_to do |format|
format.html { redirect_to post_comments_path(@post) }
format.xml { head :ok }
end
end

Ruby on Rails: Creating Delete Link Of Associated Object

<% @project.project_images.each do |image| %>
<%= image_tag image.photo.url(:thumb) %>
<div class="actions">
<%= link_to "remove", project_path(@project.id, project: { project_images: { id: image.id, "_destroy" => true }}), remote: true, confirm: "Are you sure?", method: :put %>
</div>
<% end %>

Adding a delete link for nested attributes

Why do you want to use a link? You can also use the destroy functionality in the nested attributes.

All you need to do is:

  1. Add :allow_destroy => true in your accepts_nested_attributes definition
  2. Add :_allow_destroy to your controller's strong params
  3. Add <%= l.check_box '_destroy' %> to your template

That way it removes all the nested records with the check-box checked when saving the record.

How do I put a delete link within an update form?

Another curious workaround that does not require javascript, is to put the delete-form outside the update-form but leave a <label for="theSubmitButtonInTheDeleteForm"> inside the update form.
The update-form will continue to work as expected, but clicking the label will submit the delete-form.
Then just style the label as a button.

Delete a join table entry from associated model

If you have your routes and controllers setup correctly, you can type rake routes in terminal and check out the delete path for minilines. You can send the miniature and line model with the path. Then in the controller, instead of finding by id. you can do something like this MiniLine.find_by_miniature_id_and_line_id(miniature.id, line.id), then destroy the result.



Related Topics



Leave a reply



Submit