Reputation: 601
I have two Models:
Users, and Articles
Every user is able to create an article but can only edit his own Articles?
Can someone provide an example of that? (Model, Controller and View Please?)
Thanks
EDIT
I do not want the whole code. I can get the most of the code using scaffolding. I need the modifications that I have to do to achieve that. My biggest concern is how to allow only the author of an article to edit it. That's what I am asking.
Upvotes: 0
Views: 60
Reputation: 902
Assuming an Article belongs_to :user
and you have an authentication setup that gives you a current_user
method, you should be able to do something like this in your ArticlesController:
def edit
@article = Article.find(params[:id])
if @article.user == current_user
render :edit
else
flash[:alert] = "You don't have permission to edit this article."
redirect_to some_path
end
end
You would also need something similar for your update
method.
Upvotes: 0
Reputation:
I can't write the full example code out but I can at least point you in the right direction.
You're describing a one to many association between your two models. This guide is the best I've seen in figuring out how to set up those associations in Rails.
Once you've got that in place you can limit access based on ownership of the article quite easily. For something this straight forward you probably wouldn't need a permissions gem but there are some solid ones out there.
I'd protect access in the controllers and in the view. You can simply check the current_user against the article object on the view, and in the controller you can use before filters to protect the article.
If you get further down this path and have more specific questions I'm glad to try and answer them.
Upvotes: 1