Whether to do it in hash or in model
I have a situation, wherein I have a few hundred records in a lookup table. Often times in the code, I have to lookup开发者_Python百科 the incoming values using the table.
Each such lookup results in a db trip. However optimized, that would be some cost on I/o side. I am thinking, should I not get everything in a hash. thereby reducing the no of db trips to just one.
Since its a few hundred records, I reckon that the memory consumption on the hash should not be a killer.
Looking for opinions? best practices ? experiences ?
Looking them up one at a time is needlessly wasteful. You might not notice the waste with the small numbers that you're dealing with but bad habits are bad habits and, well, good habits are better.
You should load all the entries you need with a single database hit. If you need them as objects then a Set of objects (or a hash which maps their IDs to the object) would make sense; if you only need to know if they exist, then add a method to the model something like this:
def self.valid_ids_from(ids)
# Ask the database which things in the `ids` array it has
# and put those in `ids_that_are_there`.
Set.new(ids_that_are_there)
end
Then you could do things like this:
known_ids = Pancake.valid_ids_from(incoming_ids)
good, bad = incoming_ids.partition { |x| known_ids.include?(x) }
You could use a Hash if you don't like Set, there's little difference for something like this.
As usual, the specific implementation depends on your requirements. But don't be afraid to add methods to your models that collect and massage specific collections of data.
精彩评论