i am using devise gem to handle user. users has one_to_many association with projects. and there is multiple user each user has their own dashboard but still user are able to manipulate project_id in url and able to see other users project and also able to edit delete that. how can i stop that?
user redirection after login (project#index) -
project_controller.rb
def index
@projects = current_user.projects.all.order("created_at DESC").paginate(page: params[:page], per_page: 15)
end
def show
@project = Project.includes(stages: {tasks:}).find(params[:id])
@stages = @project.stages
end
def new
@project = current_user.projects.build
end
def create
@project = current_user.projects.build(project_params)
respond_to do |format|
if @project.save
format.html { redirect_to projects_url, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: @project }
else
format.html { render :new }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
You can simply use current_user.projects
scope in show
action:
def show
@project = current_user.projects.includes(stages: :tasks).find(params[:id])
end
This way, if you edit URL and put ID belonging to another user, you'll get ActiveRecord::RecordNotFound
, which is handled as 404 error by Rails by default.
Of course, you can use this approach to secure edit
, update
and destroy
actions as well.