sessions

Hello, I have a little question.

I want to an user edit or delete their comments. For it, I have this code:

<% if post.usuario_id == session[:usuario_id] %>       <td><%= link_to 'Editar', {:action => 'edit', :id => post.id} %></td> <% end %>

You can see that post have a value "usuario_id" where the I must completed manually in the new post form. I want to change it and compare the name of the commenter:

<% if post.nombre == session[:usuario_nombre] %>

And my code of login:

def login       if request.post?         usuario = Usuario.authenticate(params[:nombre], params[:password])         if usuario #Here, I changed usuario.id to usuario.nombre to store the name's user in the session, right?           #session[:usuario_nombre] = usuario.nombre           session[:usuario_id] = usuario.id           redirect_to(:action => "index")         else           flash.now[:notice] = "Usuario o contraseña no válido"         end       end     end

I thought that it could work, but not... I have modified the if sentence and the admin_controller and I see that it works for a moment! I logged out to try with other user and I received an error. I think that, when it works, I have this:

<% if post.nombre == session[:usuario_nombre].nombre %>

And I received this error, I think:

"undefined method `nombre' for 1:Fixnum"

I'm surely that the problem is in the if sentence and/or admin_controller, in session[:param] = ...

Hi Jorge,

First of all, you mention that you have to give usuario_id manually every time you create a post. This doesn't sound right at all to me. Do you create a post from the name of a user who is currently logged in? If so, you have his usuario_id in the session, don't you? In the post#create action you create a new model instance from form parameters and set the post.usuario_id to session[:usuario_id]. Moreover, if you use one of the standard authentication plugins, you will have "current_user" available to almost any piece of the application (controllers, views, helpers), and so you can get your user ID from that.

Your check then becomes:

own_post = logged_in? && current_user.id == post.usuario_id

To push it a bit further, you may want to move this piece into the application helper, like this:

def owns?(resource)   logged_in? && current_user.id == resource.usuario_id end

And then your view becomes:

<% if owns?(post) %>       <td><%= link_to 'Editar', {:action => 'edit', :id => post.id} %></td> <% end %>

I didn't go far to the analysis of your error since the solution doesn't sound right in the first place.

Hope it helps.

- Aleksey