Storing data in a Rails array

Asked

Viewed 155 times

0

I need to store data coming 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

2 answers

0

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

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

0


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

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

If you are an association:

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

In the latter case if it is associated with a Collection and generate the problem of n+1 Voce can use includes:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.