Reputation: 629
So I have implemented a session system, but I have some troubles.
First of all, when I create a new pokemon, I link the session[:user_id] to it with this code.
@pokemon = Pokemon.new(params[:pokemon])
@pokemon.user_id = @current_user
When I create one with my account 1, the user_id is 1, but when I create a pokemon with my account 2, the user_id is set to 1 again.
Also, how can I protect the edit/show/destroy pages to sessions only ? Right now, I can edit any of the pokemons with any of the account, if I use directly the address bar.
I put my controllers in a Gist (I suppose it all happens in them)
Thanks in advance.
Upvotes: 0
Views: 23
Reputation: 21795
Maybe this is not an answer, but is too long to be a comment.
First, I am not sure @pokemon.user_id
can be set to an user instance, I would try with:
@pokemon.user = current_user
or:
@pokemon.user_id = current_user.id
Second, I would not user @current_user
, instead current_user
as above.
Third, it is not clear where you are setting session[:user_id]
, to debug your problem I would print all related variables in create action of pokemons controller:
def create
@pokemon = Pokemon.new(params[:pokemon])
@pokemon.user_id = current_user
p current_user
p session[:user_id]
You can scope your resource with current_user
:
@pokemon = current_user.pokemons.find(params[:id])
That way you will find just pokemons for that user. I am not sure if this method raises an exception or just returns nil
when user has not created pokemon with params[:id]
. You have to handle whichever of these two (exception or nil) to redirect other users to another page:
begin
@pokemon = current_user.pokemons.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
redirect_to :back
end
@pokemon = current_user.pokemons.find(params[:id])
unless @pokemon
redirect_to :back
end
Upvotes: 1