I am a second year undergrad designing a ruby on rail program for
wedding.
I am struggling so much with lots of code but one main thing which I
don't understand how to do is to make sure that if the administrator has
the rights to delete any registered users, then they don't delete their
own account in the process, as is currently the case.
Please can someone help me? I know it is a code within user
controller.rb which has "def destroy" but I don't know how to go about
doing that.
I tried the following IF statement from another website but that doesn't
seem to work. Could you suggest some correction to the below code or do
I need to change where I am putting the code in the first place?
def destroy
@user = User.find(params[:id])
if not user.role = 'admin'
@user.destroy
else
respond_to do |format|
format.html { redirect_to users_path,
notice: "#{@user.name} is an admin. You do not have
permission to delete this user" }
format.json { head :no_content }
end
end
I tried the following IF statement from another website but that doesn't
seem to work. Could you suggest some correction to the below code or do
I need to change where I am putting the code in the first place?
def destroy
@user = User.find(params[:id])
if not user.role = 'admin'
@user.destroy
else
respond_to do |format|
format.html { redirect_to users_path,
notice: "#{@user.name} is an admin. You do not have
permission to delete this user" }
format.json { head :no_content }
end
end
IMO, this isn’t good code. I recommend you look at railstutorial.org which has an online book. Chapters 6-9 give a very good tutorial on building user login functionality, how to insure only admins can delete users, and how to insure an admin can’t delete themselves. As Ganesh posted above, generally before_actions are used in the controller instead of the language you have above to insure only admins can delete users.
I believe this tutorial is good because it builds authentication from the ground up (roll your own) and you learn the concepts. In practice, I don’t usually do that because there are gems that are easier to use such as devise.