1

I have a rails 4 application. I have the following code:

@product_types = StoreProduct.where(:store_id => @store.id).pluck(:name)

@product_data = @products.map do |product|
    product[ :data ].values.reverse!
end

@product_types output looks like this: ["Color", "QTY", "TypeOf"]

@product_data output looks like this: [["RED", "17", "BOOK"]]

@products looks like: [#<Product id: 141, store_id: 146, data: {"Color"=>"RED", "QTY"=>"17", "TypeOf" => "BOOK"}>]

I want for @product_data to be sorted in the same order as @product_types. So if its QTY, Color, TypeOf as the @product_types, then the @product_data should be sorted by its keys in the same way as @product_types, so @product_data should be: 17, RED, BOOK.

2 Answers 2

2

Instead of:

@product_data = @products.map do |product|
  product[:data].values.reverse!
end

try:

@product_data = @products.map do |product|
  @product_types.map { |pt| product[:data][pt] }
end

#=> [["RED", "17", "BOOK"]]
Sign up to request clarification or add additional context in comments.

Comments

1

This might help. I am directly dealing with general Ruby constructs, mimic it for your @products:

foo = ["Color", "QTY", "TypeOf"]
bar = [{'QTY' => 17, 'TypeOf' => 'Book', 'Color' => 'Red'},
       {'Color' => 'Blue', 'QTY' => 18, 'TypeOf' => 'Gem'}]
p foo.map{ |x| bar.map { |y| y[x] } }.transpose 
#=> [["Red", 17, "Book"], ["Blue", 18, "Gem"]]

Running code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.