Home > Software engineering >  Restrict viewing based on Current_user
Restrict viewing based on Current_user

Time:04-12

I'm sure this is a silly question with a straight-forward answer, but I can't seem to recall the answer or find it in the Devise docs.

I'm looking for a way to restrict a user from seeing attributes of a record they don't own. In my application, users have_many :notes and notes belongs_to :user.

Right now, a user can look at their own post (localhost:3000/notes/1), but they can also view notes by any other user, simply by changing the url to something like localhost:3000/notes/2. I want to prevent that and only allow them the ability to view their own (~/notes/1 in this example)

CodePudding user response:

In the controller action scope the query to the current user, something like

Note.all.where(user_id: current_user.id) for index and chain with .find(id: params[:id]) for actions with single record.

CodePudding user response:

def show
   @note = @current_user.notes.find_by(id: params[:id])
end
  • Related