--Edit, update
ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
-Build login environment with devise -Posting function that only logged-in users can do
config/routes.rb
resources :posts, only: [:create, :new]
By adding the following to the above description, the route setting of edit, update, destroy.
config/routes.rb
resources :posts, only: [:create, :new, :edit, :update, :destroy]
It is OK if the following results are obtained.
Terminal
$ rails routes
...
posts POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
Add the following
app/controllers/posts_controller.rb
...
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to request.referer
else
render :new
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to request.referer
end
Create a new edit.html.erb file under app / views / posts
erb:app/views/posts/edit.html.erb
<h1>Posts#edit</h1>
<span>Currently logged in user:<%= current_user.name %></span>
<%= form_for(@post, url: post_path(@post)) do |f| %>
<div>
<%= f.label :title%><br>
<%= f.text_field :title, autofocus: true, :placeholder =>"#{@post.title}" %>
</div>
<div>
<%= f.label :contents%><br>
<%= f.text_area :body, :placeholder =>"#{@post.body}" %>
</div>
<div><%= f.submit "Update" %></div>
<% end %>
erb:app/views/posts/new.html.erb
<table>
<thead>
<tr>
<th>Posted by name</th>
<th>title</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<% @posts.each do |post| %>
<tr>
<td><%= post.user.name %></td>
<td><%= post.title %></td>
<td><%= post.body %></td>
<td><%= link_to "Edit", edit_post_path(post) %></td>← Add
<td><%= link_to "Delete", post_path(post), method: :delete %></td>← Add
</tr>
<% end %>
</tbody>
</table>
Recommended Posts