-2

I'm trying to do a search but did not get any result. This is wrong:

def BuscarRoles(usuario)
    @sql="SELECT * FROM rols WHERE id_rol IN (SELECT id_rol FROM rol_usuarios WHERE id_usuario =  "+usuario.to_s+")"
    @roles = ActiveRecord::Base.connection.execute(@sql)
    @tira='['
   if @roles.count>0
                @aroles.each do |rol|
                 @tira = @tira+" { id_rol: '" + rol.id_rol.to_s + "', descripcion: '" + rol.descripcion.to_s
                 j=j+1
                 if j<@roles.count
                  @tira = @tira+ " }, "
                 else
                  @tira = @tira+" } ] "
                 end
                end
    else
                @tira= @tira+"{ { text: 'No hay datos', id: '0', href: '', leaf: true } } ]"
    end
    return @tira
  end
Carlos Mora
  • 13
  • 1
  • 2
  • No body can understand this :( Post the trace. BTW did you check the trace and try finding out which line caused the issue ? – Pramod Solanky Dec 26 '14 at 13:38
  • the line wich caused the issue " @aroles.each do |rol|" it's like the obj was nil. but there are rows in the databae – Carlos Mora Dec 26 '14 at 13:45
  • This code is downright dangerous. A primitive query is run with raw SQL without any escaping, the result is rendered into JSON by hand. Method name is CamelCased and is confused with a constant by syntax highlighters. I'm not even talking about using models and associations. I wish you luck, sir. No sarcasm. But I humbly recommend rewriting this. – D-side Dec 26 '14 at 22:38

1 Answers1

1

By just looking at the code, with no trace given, I can only see one thing that might cause the error.

ActiveRecord::Base.connection.execute
#the result of the above code is Mysql2::Result of course depending on what database you're using.

Hence you can't use .(dot) operator on the result as you would do on a model object.

So you could make the following changes in the code

@aroles.each do |rol|
  #puts rol.id_role => this will throw error 
  puts rol[0] # this should work assuming id_role is the first column
end

That should help. As you mentioned in the comment that your getting error in @aroles.each do |rol| then you must check if the sql statement is returning you any results at all ?

BTW, even if the query doesn't return any results, it would simply return an empty array and iterating an empty array would simple give nothing but not throw any error.

So to conclude

  1. Check if any records are returned at all
  2. Use index instead of the column name as they are active_record objects

Hope that helps.

Pramod Solanky
  • 1,690
  • 15
  • 17