class Country < ApplicationRecord include TranslatableName extend FriendlyId friendly_id :name, use: :slugged # before_save :format_json_attributes, :timezones, :translations 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 serialize :translations, coder: JSON 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