user3566065
user3566065

Reputation: 1

Iterate over rails active record model?

How can I iterate over each product_category_id and return an array of modifier_id that belong to product_category_id?

Here is my db layout:

id  product_category_id modifier_id time_stamp
1         7                     5               NULL
2         7                     4               NULL
3         7                     54              NULL
4         7                     55              NULL
5         8                      6              NULL
6        93                      7              NULL
7        48                      5              NULL
8        48                      4              NULL
9        48                     55              NULL
10       48                     54              NULL
11       11                      2              NULL
12       11                      1              NULL
13       11                      10             NULL
14       11                      44             NULL

https://gist.github.com/ggeorgiev1/aaed6de2643c16bef0a7

So result should look similar to this: {:product_category_id => 7, :modifier_id => [5,4,54,55] }

Thank you

Upvotes: 0

Views: 388

Answers (3)

Dimitri Cabete Jorge
Dimitri Cabete Jorge

Reputation: 2083

If you are ok with a format such as

{ 7: [5, 4, 54, 55] }

You could do:

result = Hash.new {|k, v| k[v] = [] }

ProductCategoryDefaultModifiers.all.each do |it|
  result[it.product_category_id] << it.modifier_id
end

puts result

Upvotes: 1

nronas
nronas

Reputation: 181

You can do it with #group_by

ProductCategoryDefaultModifiers.all.group_by do |record| 
  {:product_category_id => record.product_category_id}
end

#=> {:product_category_id=>7} => [#<ProductCategoryDefaultModifier id: 1, modifier_id: 5>, ...]

Have in mind for big data set is better to use a database group

Upvotes: 1

Pavel S
Pavel S

Reputation: 1543

Just to have array of modifiers for product category = 7

modifiers = ProductCategoryDefaultModifier.select(:modifier_id).where(product_category_id: 7).pluck(:modifier_id)

or you can have them all in a hash where key will be product_category_id

ProductCategoryDefaultModifier.all.group_by{|pcdm| pcdm.product_category_id}

Upvotes: 0

Related Questions