hl1hta
Last Updated: February 25, 2016
·
1.162K
· tconst
Screen shot 2016 11 21 at 5.48.25 pm

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

Say Thanks
Respond

2 Responses
Add your response

1062
B61ce134adf2d6eb1d1f1d11122d6142

@tconst nice catch!

over 1 year ago ·
1063
Screen shot 2016 11 21 at 5.48.25 pm

@phlipper thanks!

over 1 year ago ·