Answer the question
In order to leave comments, you need to log in
How to limit view output in rails?
Good afternoon!
There are User and Post entities, the most common has_many\belongs_to association between them.
Question:
How can I make the user see and edit/delete only his own posts?
Currently done like this:
#posts_controller.rb
def index
@posts = current_user.posts.all
end
Answer the question
In order to leave comments, you need to log in
Make a method that will compare the user id with the id of the user who created the post.
If they match, then the user can edit - if not, then the user is not the author and cannot edit.
In a nutshell and quickly
def user_author?(user, post)
if user.id == post.user.id
true
else
false
end
end
helper_method :user_author? #скажем рельсам чтобы метод был доступен и из view
ApplicationController
flash[:error] = 'Вы не можете редактировать пост - вы не являетесь автором'
def current_user?(user)
user == current_user
end
helper_method :current_user?
#posts_controller.rb
def edit
@post = Post.find(params[:id])
unless current_user?(@post.user)
redirect_to root_path
flash[:error] = 'Вы не можете редактировать пост - вы не являетесь автором'
end
end
def update
@post = Post.find(params[:id])
if current_user?(post.user)
#редактируем и сохраняем
else
redirect_to root_path
flash[:error] = 'Вы не можете редактировать пост - вы не являетесь автором'
end
end
#posts_controller.rb
def index
@posts = current_user.posts #.all необязательно
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question