`rails db:seed` failed (NameError due to heredoc interpolation)
Context: I ran the generated seed script which populated Learning
records from LEARNINGS.md
. The error occurred processing an entry whose body contained the literal text params[:tag]
. The default heredoc syntax (<<~BODY
) attempted Ruby interpolation (#{...}
) on this text, causing NameError: undefined local variable or method 'params' for main:Object
.
Resolution: I changed the heredoc definition for the problematic entry in db/seeds.rb
from <<~BODY
to <<~'BODY'
(note the single quotes). This prevents interpolation within that specific string, treating it literally.
Learning: I learned to be cautious when using interpolating heredocs (<<~DELIMITER
) in seed files or scripts if the source text might contain #{}
, ${}
, or similar sequences that could be misinterpreted as code interpolation. Use non-interpolating heredocs (<<~'DELIMITER'
) or escape the relevant characters (\#{}
) within the string if interpolation is needed elsewhere but not for specific literals.
Learned on: April 20, 2024
Edit