(Ruby on Rails6) "Erase" posted content

Preface

Here, RubyonRails6 is used to record an oblivion record that edits (erases) </ strong> the posted content. In the previous post, Implemented editing function . The implementation of the editing function is recorded there, so if you want to check it, please check there.

"Erase" the posted content

To implement this post, action </ strong> should be erase (click) data / transfer to post list </ strong>.

routes settings

Create a delete action </ strong> in routes. With form /: id / delete </ strong>, the URL of the id you want to delete is specified. Also, if you want to modify </ strong> the database, set it with "post" </ strong> instead of "get" on routes.

config/routes


・
・
・
post "form/:id/delete" => "form#delete"

Link setting to View

erb:app/views/Any.html.erb


・
・
・
<%= link_to("Delete", "/form/#{@post.id}/delete", {method: "post"}) %>

I'm using link_to </ strong> to link to the delete action I just created.

Note: Difference between get and post

By adding {method: "post"}) </ strong>, you can associate it with the post of routes. It's complicated !!

erb:app/views/Any.html.erb


↓ error in post
<%= link_to("Delete", "/form/#{@forms.id}/delete") %>

↓ is correct
<%= link_to("Delete", "/form/#{@forms.id}/delete", {method: "post"}) %>

Extract and delete data

app/controllers/Any.rb


  def delete
    @forms = Form.find_by(id: params[:id])
    @forms.destroy
    
    redirect_to("/")
  end

↑ Details

app/controllers/Any.rb


  def delete
    # find_Get data with by method
    @forms = Form.find_by(id: params[:id])
  end

app/controllers/Any.rb


  def delete
    # @table name.Delete with destroy
    @forms.destroy
  end

app/controllers/Any.rb


  def delete
    # redirect_Set redirect with to method
    redirect_to("/")
  end

If the above is completed and the error does not get angry, the delete function should be completed. How was it?

Afterword

Thank you for reading this far. It looks like a full-fledged site if you implement the display / modification function from the database settings and add the delete function to the post. However, when the posting function is successfully deleted, I feel happy but sad (Why?)

Database creation / editing / delete and basic functions have been implemented so far. I would like to learn about security and detailed functions in the future.

Reference link

<a href="https://www.amazon.co.jp/Ruby-Rails-%E5%AE%9F%E8%B7%B5%E3%82%AC%E3%82%A4%E3%83% 89-impress-gear / dp / 4295008052 "target =" blank "> Ruby on Rails6 Practical Guide

My link

Also, there is a link on Twitter / Portfolio, so if you are interested, Please connect. I would be very happy to have friends who can share programming learning.

Twitter Portfolio Github

Recommended Posts