I run a before_filter on some actions to check if the user is the current_user.
before_filter :correct_user, :only => [:edit, :update, :destroy]
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
redirect_to current_user, :notice => "User updated!"
else
redirect_to current_user, :notice => "User not updated. waa waa."
end
end
private
def correct_user
if current_user != @user
redirect_to root_url, :notice => "Cannot act on different user."
end
end
Not sure if this is the best way to do things, but it works (maybe it is better practice to simply use current_user instead of finding @user via params?)
Now User has_many photos, and in my photos index view, I list all the user’s photos and allow for the user to set any one photo as a profile photo. The user table has a column called primary_photo_id, to hold this ID, and I use a link_to to set this:
=link_to "Make this your profile photo", user_path(@user, :user => {:primary_photo_id => "#{photo.id}"}), :method => :put
The problem is that the before_filter kicks in and will prevent this from working because the @user that is retrieved via params[:id] fails because it is not the right params. If I remove the before_filter, it works fine but then it’s not checking for the correct user anymore.
(a second somewhat related question is why the above code works but this one:
=link_to "Make this your profile photo", user_path(@user, :primary_photo_id => "#{photo.id}"), :method => :put
doesn’t.
Thanks. I’m pretty new to rails and programming so anything you can say regarding my specific question, and any bad practices I’m doing with the code here, is very much appreciated.
The before filter (
#correct_user) runs before#update, so your instance variable@userisn’t set yet when you are comparing it in the filter if you haven’t set it in another before filter first. Your execution sequence looks like:#correct_user– compare current_user to@user(if unset, this is nil). these will only ever match if the user isn’t logged in I’m guessing@userProbably the easiest way to address your problem is just to move the
@userlookup into the before filter:Since
@useris now being located in the filter, there is no need to look it up again in each of your controller actions. Hope this helps!