I was trying to create a field which is datatype of Array through migration and it did got updated in schema.rb file.
However my main goal was to give fixed value to this field (ie Array), which is not going to change in future. Kind of static value.
I applied this method to create a field.
rails generate migration Store_detailsToAdmin store_details:string
Admin.rb file.
serialize :store_details, Array
rake db:migrate
Can anyone help me have default and fixed values on this column?
Set default value as "xyz"
class Admin < ApplicationRecord
serialize : store_details, Array
after_initialize -> { self. store_details.blank? ? self. store_details.push('xyz') : self. store_details }
end
Get default value of it if array is blank
admin.store_details => ["xyz"]
Add another value in it
admin.store_details.push("abc")
admin.save
admin.store_details => ["xyz", "abc"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.