23
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsで投稿の編集、削除機能

Last updated at Posted at 2018-04-07

編集機能の流れ

  • editページへ飛ばす
  • editページでもともとの値をデフォルトで出す
  • updateメソッドで変更

form

form_tagで書く場合

edit.html.erb
<%= form_tag("/posts/#{@post.id}/update") do %>
 <form>
  <div class="form-group">
   <label for="exampleInputEmail1">編集する</label>
   <textarea name="title" class="form-control"><%= @post.title %></textarea>
  </div><!--form-group-->
  <button type="submit" class="btn btn-primary">保存</button>
<% end %>

form_withで書く場合

edit.html.erb
<%= form_with model: @user do |form| %>
  <%= form.text_area :user_name, id: "user_name" %>
  <%= form.submit "更新する" %>
<% end %>
routes.rb
post "posts/:id/update" => "posts#update"
post_controller.erb
  def edit
    @post = Post.find_by(id: params[:id])
  end
  def update
    @post = Post.find_by(id: params[:id])
    @post.update(title: params[:title])
    redirect_to("/")
  end

form_withでmodelで書いた場合はpostの中にネストした形でparamsがくるのでparams[:post][:title]などになる点に注意

削除機能の流れ

  • destroycontrollerへrouteを飛ばす
  • controllerでdestroy
show.html.erb
     <%= link_to("/posts/#{@post.id}/destroy",{method:"post"}) do %>
     <button type="button" class="btn btn-outline-primary">
       <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 削除
     </button>
     <% end %>
routes.rb
post "posts/:id/destroy" => "posts#destroy"
post_controller.erb
  def destroy
    @post = Post.find_by(id: params[:id])
    @post.destroy
    redirect_to("/")
  end

よくある間違え

destroyしたあとはそのページは消えているのでredirect_to("/")で

23
28
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?