Rails migrations: Interpolate values/dynamic content

Rails migrations: Interpolate values/dynamic content

Did not know that you can interpolate values in you migrations, so that way you can have dynamic content in a default value in your model.

This is the basic example:

Gemfile

gem 'liquid'

Your migration

class AddMyFieldToTableName < ActiveRecord::Migration
  def change
      add_column :table_name, 
                 :my_field, 
                 :text, 
                 default: '{% if value != nil %}<h1>some values here {{my_name}}</h1>{% endif %}'
        
  end
end

Let’s interpolate the values: Maybe in your serializer or controller:

params = {
  value: true,
  my_name: 'heriberto perez magaña'
}

content = Liquid::Template.parse(MyModel.my_field).render(params)
content.html_safe

That’s it.

No Comments

Post A Comment