2025-01-19 12:21:00 +08:00
|
|
|
class City < ApplicationRecord
|
|
|
|
extend FriendlyId
|
2025-01-22 14:04:58 +08:00
|
|
|
friendly_id :slug_candidates, use: :slugged
|
2025-01-21 18:27:26 +08:00
|
|
|
belongs_to :country
|
2025-01-19 12:21:00 +08:00
|
|
|
|
|
|
|
has_many :weather_arts, dependent: :destroy
|
|
|
|
|
|
|
|
validates :name, presence: true
|
|
|
|
validates :latitude, presence: true
|
|
|
|
validates :longitude, presence: true
|
|
|
|
|
2025-01-21 18:27:26 +08:00
|
|
|
delegate :region, to: :country
|
|
|
|
|
2025-01-22 14:04:58 +08:00
|
|
|
scope :by_region, ->(region_id) { joins(:country).where(countries: { region_id: region_id }) }
|
|
|
|
scope :by_country, ->(country_id) { where(country_id: country_id) }
|
|
|
|
scope :active, -> { where(active: true) }
|
|
|
|
|
2025-01-21 18:27:26 +08:00
|
|
|
def to_s
|
|
|
|
name
|
|
|
|
end
|
|
|
|
|
2025-01-22 14:04:58 +08:00
|
|
|
def slug_candidates
|
|
|
|
[
|
|
|
|
:name,
|
|
|
|
[ :country, :name ]
|
|
|
|
]
|
|
|
|
end
|
|
|
|
|
2025-01-21 18:27:26 +08:00
|
|
|
def localized_name
|
|
|
|
I18n.t("cities.#{name.parameterize.underscore}")
|
|
|
|
end
|
|
|
|
|
|
|
|
def full_name
|
|
|
|
"#{name}, #{country}"
|
|
|
|
end
|
|
|
|
|
2025-01-19 12:21:00 +08:00
|
|
|
def should_generate_new_friendly_id?
|
|
|
|
name_changed? || super
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.ransackable_associations(auth_object = nil)
|
|
|
|
[ "weather_arts" ]
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.ransackable_attributes(auth_object = nil)
|
2025-01-20 18:08:55 +08:00
|
|
|
[ "active", "country", "created_at", "id", "id_value", "last_image_generation", "last_weather_fetch", "latitude", "longitude", "name", "priority", "region", "slug", "timezone", "updated_at" ]
|
2025-01-19 12:21:00 +08:00
|
|
|
end
|
|
|
|
|
2025-01-20 18:02:28 +08:00
|
|
|
def latest_weather_art
|
|
|
|
weather_arts.order(weather_date: :desc).first
|
|
|
|
end
|
2025-01-19 12:21:00 +08:00
|
|
|
end
|