Last Updated: February 25, 2016
·
1.388K
· tconst

when not to use rails memoization

I was recently working on some code and came accross a good example of when not to use rails memoization. The following example is probably extremely obvious but was overlooked by a few experienced rails devs.

So lets say our model stores a markup rate for each product in its table. We want to assign a calculated value to this rate based on the store selling the product. So we do this with the code in the model below.

before_validation :set_defaults

def markup_rate
  self[:markup_rate] ||= some_calcuation_code_here
end

private

def set_defaults
   self.markup_rate
end

What is wrong with this? Mass assignment will set these via params if passed. Anyone could pass through the markup_rate as a param and really screw up your fee calculations (scary). Some would think you could just add

attr_protected :markup_rate

and be all set, right? Unfortunately no, that will not work here. We are assigning the markuprate outside of our massassignment, so attr_protected will not work here.

TL;DR; don't use memoization on fields that shouldn't be assigned via mass_assignment

2 Responses
Add your response

@tconst nice catch!

over 1 year ago ·

@phlipper thanks!

over 1 year ago ·