Saving data in an array in Rails

0

I need to store data from a database search in an array, but with the code below it only stores a value in the array.

@busca= Item.find(:all,:conditions=>{:codigo=>params[:codigo]})
@busca.each do|buscador|
@novamatriz=Array.new
@novamatriz.append(buscador.modelo)
end
    
asked by anonymous 22.02.2016 / 14:10

2 answers

0

A slightly more elegant solution. If modelo is a simple value (string, int):

@lista = Item.where(codigo: params[:codigo]).pluck(:modelo)

If it's an association:

@lista = Item.where(codigo: params[:codigo]).map(&:modelo)

In the latter case, if you are associating with a collection and generating the n + 1 problem, you can use includes :

@lista = Item.includes(:modelos).where(codigo: params[:codigo]).map(&:modelo)
    
22.02.2016 / 16:31
0

I was able to identify the error, I was creating a new array all the time. I solved only by taking the creation of the array of each structure.

@busca= Item.find(:all,:conditions=>{:codigo=>params[:codigo]})
@novamatriz=Array.new
@busca.each do|buscador|
@novamatriz.append(buscador.modelo)
end
    
22.02.2016 / 14:17