I want to create a hash (using Base64) based on a composite of foreign keys from a collection of children objects that belong to a parent.
class Basket < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :basket
belongs_to :mfg
belongs_to :locale
end
So let’s say that we have a basket object that has three item objects:
Item #1
– mfg_id: 1
– locale_id : 2Item #2
– mfg_id: 3
– locale_id : 4Item #3
– mfg_id: 5
– locale_id : 6
The hash would like something like:
Base64.encode64(12-34-56)
My question really is what’s the most efficient way in ruby to create such a hash? If it were just a few children objects to iterate over, then I wouldn’t be too worried about efficiency; however, in my case there could be a lot so I’d like your input on the most efficient way that you can recommend to construct the hash.
Maybe:
There should a monstrous quantity of items for something like this to be inefficient (because of the creation of the intermediate array). You can also use inject to build the string inplace and avoid the intermediate array, but that’s pretty ugly compared to
map+join.And using pure SQL (not so portable, but faster):