I’ve got a quality_code field which is free-text entered by the user. However, there are certain known codes with a longer description available. If a known code is stored on the record, I would like to display the description in place of the code.
I’ve got a simple method on the model to show the description if available, or the entered quality_code if not, but it falls into the typical pattern of n+1 queries required to draw a list of n items:
def view_quality_code
if (code = QualityCode.find_by_quality_code(quality_code)).nil?
quality_code
else
code.description
end
end
If the models were actually linked (belongs_to :quality_code) then I would sort this out by adding includes(:quality_code) to the query, so it would just do one extra query to the quality_code table.
Is there a simple way to do the same sort of thing without the models being linked?
Not knowing what your other model is called, I’ll pretend it’s “Widget.” Assuming you have an array of widgets like so:
You can fake the eager loading yourself like this: