I already have a date field (string) in my model. I plan to add other string fields with different long date formats to use in a text search related to the existing date field. This is to facilitate text searching for the visually impaired.
I have done something like this before which worked just fine.
add_column :media_libraries, :media_year, :string, default: Time.now.year
However what I want to do is to add the date fields and default the new date field using the value of an existing date field.
I have the code below in one of my views which has the field I want to use to initialize the value of the new long date fields.
media_created.to_date
Can I do something like this in my migration where I can set a default value depending on the value of another field on the record?
add_column :media_libraries, :media_created_en, :string, default: :media_created.to_date.strftime("somedateformat")
I have read another post add a database column with Rails migration and populate it based on another column where one of the answers suggested a query within the migration. This would be my attempt to implement that. However others posting on Stack Overflow feel that it is not a good idea to reference other fields in a migration. For me since this is a one-time thing I'm not worried about those issues.
MediaLibrary.update_all(media_created_en: :media_created.to_date.strftime("%B %d, %Y"), media_created_fr: :media_created.to_date.strftime("%d %B %Y"), media_created_pt: :media_created.to_date.strftime("%d %B %Y"), media_created_es: :media_created.to_date.strftime("%d de %B de %Y"))
I want to do this for existing records since I have over 1000 records to update. I will either put code in my model or my controller to set the fields for future updates to the model.
I have looked everywhere but can only find built-in functions used for default or the one example above. The API says nothing other than 'options{}'. If this cannot be done I am ready to write a method to do this one time in the admin section of my application.
Any help will be appreciated. I will keep searching.