Reputation: 85
Lets start off with i am new to programming in rails and trying to learn by building a project. I am creating a project that has following and follower capability similar to twitter... I have implemented the option to delete a post. However, it seems that i can delete other people post as well that i am following etc. How can i implement the delete of my own post and have other user have the ability to edit modify and delete their own post.
class Post < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :content, presence: true, length: { maximum: 140 } #
default_scope -> { order(created_at: :desc) } # newest tweets / posts first
end
def destroy
@status_update = Post.find(params[:id])
if @status_update.present?
@status_update.destroy
end
redirect_to root_url
end
<%= link_to('Delete', post_path(@p), :method => :delete,data: { confirm: "Are you sure?" } ) %>
i was also looking at something like this:
def owned_post
unless current_user == @post.user
flash[:alert] = "That post doesn't belong to you!"
redirect_to root_path
end
end
Upvotes: 2
Views: 623
Reputation: 2017
Lets say you have a Post
model and views all set up:
In your views/posts/show
you can set up something like this:
<% if @post.user.id == current_user.id %>
<%= link_to "Edit", edit_post_path(@post), class:"btn btn-success btn-sm" %>
<% end %>
You will still have a small issue, users can still access the form to edit, so now in your views/posts/edit
it renders a form so put a condition on it:
<% if user_signed_in? %>
<% if @post.user.id == current_user.id %>
<%= render 'form', tutorial: @post %>
<% end %>
<% else %>
<h1>stop trying to edit others post</h1>
<% end %>
Upvotes: 2
Reputation: 8710
On view specify something like this:
<% if user_signed_in? && current_user.id == @post.user_id %>
# something like edit. links... delete links..
<% end %>
or you can also use gem like: cancancan
Upvotes: 1
Reputation: 7522
Good question, though there isn't one single answer I can give you. The question of "authorization" of actions in your app is a big one, and there are gems like Pundit that you could look into for a full-fledged solution.
However, it's always good to start with the basics on your own and build up to a bigger solution. What you have already isn't wrong -- just add before_action :owned_post, only: [:delete]
(perhaps rename to ensure_post_owner
or such) to your controller to enforce your rule.
Another option is to scope your ActiveRecord queries to the set of objects your current user is allowed to operate on. So instead of @post = Post.find(params[:id])
, you could do, @post = current_user.posts.find(params[:id])
. If the user tries to modify a post they don't own, they'll get back a 404 as if that post simply doesn't exist. This can be a good strategy to avoid letting attackers enumerate which posts are and aren't in your database.
Upvotes: 1