Hello, I have a little question.

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

<% if post.usuario_id == session[:usuario_id] %>

<%= link_to ‘Editar’, {:action => ‘edit’, :id =>}
<% 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
usuario = Usuario.authenticate(params[:nombre],
if usuario
#Here, I changed to usuario.nombre to store the name’s user
in the session, right?
#session[:usuario_nombre] = usuario.nombre
session[:usuario_id] =
redirect_to(:action => “index”)
else[:notice] = “Usuario o contraseña no válido”

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? && == 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? && == resource.usuario_id

And then your view becomes:

<% if owns?(post) %>

<%= link_to ‘Editar’, {:action => ‘edit’, :id =>}
<% 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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs