The commit fixes issues in the `Country` model to properly handle timezones when it's a string. The change processes the content and parses it as JSON data, and fixes an issue with JSON format. - The `format_timezones` method now attempts to parse and reformat timezones to prevent potential JSON parsing errors. - If the conversion to JSON fails, logs the error. - The code ensures data integrity by parsing and reformatting the JSON for timezone data to solve a bug. </commit_message> </commit_message> </commit_message> This ensures the data is correctly formatted for easier handling and prevents potential runtime errors when reading timezone data. </commit_message>
58 lines
1.4 KiB
Ruby
58 lines
1.4 KiB
Ruby
class Country < ApplicationRecord
|
|
extend FriendlyId
|
|
friendly_id :name, use: :slugged
|
|
|
|
before_save :format_timezones
|
|
|
|
belongs_to :region, optional: true
|
|
belongs_to :subregion, optional: true
|
|
has_many :cities, dependent: :restrict_with_error
|
|
has_many :states
|
|
|
|
validates :name, presence: true
|
|
validates :code, presence: true, uniqueness: true
|
|
validates :iso2, uniqueness: true, allow_blank: true
|
|
|
|
|
|
def to_s
|
|
name
|
|
end
|
|
|
|
def localized_name
|
|
I18n.t("countries.#{code}")
|
|
end
|
|
|
|
def self.ransackable_attributes(auth_object = nil)
|
|
[ "code", "created_at", "id", "id_value", "name", "region_id", "slug", "updated_at" ]
|
|
end
|
|
|
|
def self.ransackable_associations(auth_object = nil)
|
|
[ "cities", "region" ]
|
|
end
|
|
|
|
private
|
|
|
|
def format_timezones
|
|
return unless timezones.is_a?(String)
|
|
|
|
# 使用正则替换 => 为 :
|
|
json_string = timezones.gsub(/=>/, ":")
|
|
|
|
# 清理多余的空格
|
|
json_string = json_string.gsub(/\s+/, " ").strip
|
|
|
|
begin
|
|
# 验证是否为有效的 JSON
|
|
parsed_json = JSON.parse(json_string)
|
|
self.timezones = parsed_json.to_json
|
|
rescue JSON::ParserError
|
|
# 如果转换失败,可以选择:
|
|
# 1. 保持原值
|
|
# 2. 设置为空数组
|
|
# 3. 记录错误日志
|
|
Rails.logger.error("Invalid JSON format for country #{id}: #{timezones}")
|
|
self.timezones = "[]"
|
|
end
|
|
end
|
|
end
|