D
D
DmitryGayduk2014-09-24 16:04:38
Ruby on Rails
DmitryGayduk, 2014-09-24 16:04:38

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

However, this is not an option. Any user can go to any post via a direct link.
How do they proceed in this case?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanKiLL, 2014-09-24
@FanKiLL

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

Add a method to ApplicationController
If you already have a logged in user, then you can write the code in a different way. But the meaning will remain the same to check if the user is the author of the post, if yes - give edit - no redirect and show
flash[:error] = 'Вы не можете редактировать пост - вы не являетесь автором'

I see you already have current_user then you can write like this
def current_user?(user)
  user == current_user
end

helper_method :current_user?

And further
#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

A
anyd3v, 2014-09-24
@anyd3v

https://github.com/ryanb/cancan ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question