--Prevent other users from editing URLs with solid URLs --Do not display on the view screen in the first place
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 -Post editing function (update, delete)
Basically, (1) Use the if statement to narrow down by current_user, etc. ② Whether to extract the model associated with current_user Only the user who posted can edit it.
Description in the premise state
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 new_post_path
else
render :edit
end
end
def destroy
@posts = Post.all
@post = Post.find(params[:id])
@post.destroy
end
If you hit the URL as it is, you can edit and delete it. Therefore, write as follows.
app/controllers/posts_controller.rb
def edit
@post = Post.find(params[:id])
unless @post.user == current_user
redirect_to new_post_path
end
end
def update
@post = Post.find(params[:id])
if @post.user != current_user
redirect_to new_post_path
else
if @post.update(post_params)
redirect_to new_post_path
else
render :edit
end
end
end
def destroy
@posts = Post.all
@post = Post.find(params[:id])
if @post.user != current_user
redirect_to new_post_path
else
@post.destroy
end
end
However, this requires a lot of description, and it takes time to correct it. So use before_action.
app/controllers/posts_controller.rb
before_action :ensure_user, only: [:edit, :update, :destroy]
...
def edit
end
def update
if @post.update(post_params)
redirect_to new_post_path
else
render :edit
end
end
def destroy
@post.destroy
redirect_to new_post_path
end
private
def ensure_user
@posts = current_user.posts
@post = @posts.find_by(id: params[:id])
redirect_to new_post_path unless @post
end
...
Before URL solid printing, it is desirable not to display it on the screen to prevent user misidentification.
erb:app/views/posts/new.html.erb
<% @posts.each do |post| %>
<tr>
<td><%= post.user.name %></td>
<td><%= post.title %></td>
<td><%= post.body %></td>
<td><%= link_to "Details", post_path(post) %></td>
<td><%= link_to "Edit", edit_post_path(post) %></td>
<td><%= link_to "Delete", post_path(post), method: :delete %></td>
</tr>
<% end %>
Correct this part.
erb:app/views/posts/new.html.erb
<% @posts.each do |post| %>
<tr>
<td><%= post.user.name %></td>
<td><%= post.title %></td>
<td><%= post.body %></td>
<td><%= link_to "Details", post_path(post) %></td>
<% if post.user == current_user %>
<td><%= link_to "Edit", edit_post_path(post) %></td>
<td><%= link_to "Delete", post_path(post), method: :delete %></td>
<% else %>
<td></td>
<td></td>
<% end %>
</tr>
<% end %>
By editing the controller and view, it is possible to prevent editing by other users.
Recommended Posts