feat: add sync_city task for city data synchronization

- Define a new Rake task `sync_city` to synchronize city data
- Update the `find_or_create_by!` method to include additional
  attributes such as `flag`, `wiki_data_id`, `active`, and
  `priority`

This new task allows for better management of city data by
ensuring that all relevant attributes are set during the
synchronization process. It enhances the existing functionality
by providing more detailed information for each city.
This commit is contained in:
songtianlun 2025-02-26 11:58:10 +08:00
parent e219b53bab
commit 26f8d56632

View File

@ -15,6 +15,12 @@ namespace :geo do
sync_cities(base_path)
end
task sync_city: :environment do
# 定义 JSON 文件路径
base_path = Rails.root.join("lib", "data")
sync_cities(base_path)
end
def sync_regions(base_path)
file_path = base_path.join("regions.json")
regions = JSON.parse(File.read(file_path))
@ -164,17 +170,17 @@ namespace :geo do
country = Country.find_by!(code: data["country_code"])
state = State.find_by(code: data["state_code"])
city = City.find_or_create_by!(
name: data["name"],
country_id: country.id,
country_code: country.code,
state_code: state&.code,
state_id: state&.id,
) do |c|
c.country_id = country.id,
c.country_code = country.code,
c.latitude = data["latitude"],
city = City.find_or_create_by!(name: data["name"]) do |c|
c.country_id = country.id
c.country_code = country.code
c.latitude = data["latitude"]
c.longitude = data["longitude"]
c.state_id = state&.id
c.state_code = state&.code
c.flag = data["flag"] || true
c.wiki_data_id = data["wikiDataId"]
c.active = false
c.priority = 10
end
puts "Syncing City[#{count}/#{sum}] [#{data["name"]}] Country:[#{country&.name}] "