I’m building a small web app that allows users to list their goals. I want the users to only be able to edit their own content. I’ve already got an authenticate function as a before_filter which checks to make sure someone is signed in, but it doesn’t check if the user is the creator of the content. I tried creating a second before_filter called correct_user that has the code as follows:
def correct_user
@user = User.find(params[:id])
redirect_to(user_path(current_user)) unless current_user?(@user)
end
In addition here is the server output from running a get request to edit my own content
Started GET "/goals/31/edit" for 127.0.0.1 at 2011-05-18 15:22:38 -0400
Processing by GoalsController#edit as HTML
Parameters: {"id"=>"31"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 101) LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 31) LIMIT 1
Redirected to http://localhost:3000/users/101 Completed 302 Found in 49ms
Completed 302 Found in 49ms
For clarity, the user_id I’m using is 101, and the goal_id I’m trying to edit is 31. Could someone explain exactly what is going on?
Also, I’m aware you can navigate this problem by using a gem called CanCan (as a similar question was answered about this), but is there a way to do it without using a gem? It seems like my simple little function should work, but could someone explain why it doesn’t?
paramsis the hash of all parameters being sent (via url or form fields, etc) to your action. The name of the parameter, if present in the URL, is defined in your routes file. For your goals controller routes, you probably (presumably) have:Because you are getting
/goals/31/edit,params[:id]is 31, the id of the goal you are editing. The first line incorrect_useris finding the User whose id matches the id in the params hash (goal_id). So really, you should be doing something like this:This says, find the goal that somebody wants to edit (from params[:id]), and give me the user associated with it ( you didn’t post your goal model, I am assuming Goal belongs_to :user but you may have named it “creator” or “owner” instead). Redirect if the user is not the same as the current user logged in. Your previous code was attempting to find a User with the same id as the goal being edited.