OtavioLipari
OtavioLipari

Reputation: 85

Insert values from active record into a hash

I have this:

produtos = LineItem.select('codigosku, quantity').where("cart_id = #{session[:cart_id] } ")

I need to insert the result of this select (produto variable), here:

message = Hash.new
      message = { 
        "tem:carrinho" => {"gpa:CEP" => params[:cep],
                      "gpa:CNPJ" => 'doc', 
                      "gpa:IdCampanha" => 1111, 
                      "gpa:Produtos" => {"gpa:DadosListaProdutoCarrinhoDTO" => 
                          {

                               HERE! VALUES OF "PRODUTOS VARIABLE"


                          }
                        }
                      }
                }

How can I do this?

Thanks in advance!

Upvotes: 0

Views: 719

Answers (2)

house9
house9

Reputation: 20614

like in apneadiving example, use map to create an array from the produtos data; use attributes to return all data (it is a hash) from your selected data

message = { 
  "tem:carrinho" => {
    "gpa:CEP" => params[:cep],
    "gpa:CNPJ" => 'doc', 
    "gpa:IdCampanha" => 1111, 
    "gpa:Produtos" => {
      "gpa:DadosListaProdutoCarrinhoDTO" => produtos.map { |item| item.attributes } 
    } 
  }
}

or if you need to be more specific about the keys in the produtos and append it after initialization

# initialize the Produtos to nil
message = { 
  "tem:carrinho" => {
    "gpa:CEP" => params[:cep],
    "gpa:CNPJ" => 'doc', 
    "gpa:IdCampanha" => 1111, 
    "gpa:Produtos" => nil
  }
}        

# build an array of DadosListaProdutoCarrinhoDTO
list = produtos.map do |item| 
  {
    "gpa:DadosListaProdutoCarrinhoDTO" => {
      "codigosku" => item.codigosku, 
      "quantity" => item.quantity
    }
  }
end

# set the Produtos key to an array of DadosListaProdutoCarrinhoDTO
message["tem:carrinho"].merge!({ "gpa:Produtos" => list })

Upvotes: 1

apneadiving
apneadiving

Reputation: 115521

create your array:

line_items_array = line_items.map{|li| li.attributes }

Then insert the array within your hash.

Upvotes: 2

Related Questions