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:
- Add
:allow_destroy => true
in youraccepts_nested_attributes
definition - Add
:_allow_destroy
to your controller's strong params - 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
Ruby: Create a String from Bytes
Why Is Safe Navigation Better Than Using Try in Rails
What Is the Use of "#!/Usr/Local/Bin/Ruby -W" at the Start of a Ruby Program
How to Change the Position of an Array Element
Monkey-Patching VS. S.O.L.I.D. Principles
Phusion Passenger Error: You Have Activated Rack 1.2.1, But Your Gemfile Requires Rack 1.2.2
Rails-Like Database Migrations
Programming Technique: How to Create a Simple Card Game
Converting Utc Timestamp to Iso 8601 in Ruby
Count the Number of Lines in a File Without Reading Entire File into Memory
Ruby/Rails CSV Parsing, Invalid Byte Sequence in Utf-8
How to Get Constants Defined by Ruby's Module Class via Reflection
How to Find the Source File for a Rake Task
Rspec: How to Test File Operations and File Content