0

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.

4

1 回答 1

0

我一直在研究,但一无所获,所以我决定在迁移中尝试一些事情。我无法成功地将模型上的字段合并到我的默认值中。由于时间紧迫,我决定只在迁移中创建字段,然后在控制器中编写一个方法来更新模型上的字段。现在我将编写代码来更新要添加的记录的字段,以确保正确更新字段。

如果有人对此有解决方案,请在此处发布,但我正在继续。

于 2013-08-07T16:03:18.663 回答