- Change query conditions in City model to use the `properties::jsonb` syntax for compatibility. - Update WeatherArt model's event counting to reflect the same JSONB handling for consistency across models. These changes ensure that the queries correctly access the JSONB fields in the database, which enhances robustness when handling different database adapters like Postgres or SQLite. This fixes potential issues with ahoy events not being counted accurately due to incorrect property access.
54 lines
2.1 KiB
Ruby
54 lines
2.1 KiB
Ruby
class WeatherArt < ApplicationRecord
|
|
extend FriendlyId
|
|
friendly_id :weather_date, use: :slugged
|
|
|
|
belongs_to :city
|
|
has_one_attached :image
|
|
|
|
has_many :visits, class_name: "Ahoy::Visit", foreign_key: :weather_art_id
|
|
has_many :events, class_name: "Ahoy::Event", foreign_key: :weather_art_id
|
|
|
|
validates :weather_date, presence: true
|
|
validates :city_id, presence: true
|
|
|
|
scope :by_popularity, -> {
|
|
if ActiveRecord::Base.connection.adapter_name.downcase == "sqlite"
|
|
joins("LEFT JOIN ahoy_events ON json_extract(ahoy_events.properties, '$.weather_art_id') = weather_arts.id
|
|
AND json_extract(ahoy_events.properties, '$.event_type') = 'weather_art_view'")
|
|
.group("weather_arts.id")
|
|
.select("weather_arts.*, COUNT(ahoy_events.id) as visit_count")
|
|
.order("visit_count DESC")
|
|
else
|
|
joins("LEFT JOIN ahoy_events ON (ahoy_events.properties::jsonb->>'weather_art_id')::integer = weather_arts.id
|
|
AND ahoy_events.properties::jsonb->>'event_type' = 'weather_art_view'")
|
|
.group("weather_arts.id")
|
|
.select("weather_arts.*, COUNT(ahoy_events.id) as visit_count")
|
|
.order("visit_count DESC")
|
|
end
|
|
}
|
|
|
|
def should_generate_new_friendly_id?
|
|
weather_date_changed? || city_id_changed? || super
|
|
end
|
|
|
|
def to_s
|
|
"#{city.name} - #{weather_date.strftime('%Y-%m-%d')}"
|
|
end
|
|
|
|
def self.ransackable_associations(auth_object = nil)
|
|
[ "city", "image_attachment", "image_blob" ]
|
|
end
|
|
|
|
def self.ransackable_attributes(auth_object = nil)
|
|
[ "city_id", "cloud", "created_at", "description", "feeling_temp", "humidity", "id", "id_value", "precipitation", "pressure", "prompt", "temperature", "updated_at", "visibility", "weather_date", "wind_scale", "wind_speed" ]
|
|
end
|
|
|
|
def view_count
|
|
if ActiveRecord::Base.connection.adapter_name.downcase == "sqlite"
|
|
Ahoy::Event.where("json_extract(properties, '$.event_type') = 'weather_art_view' AND json_extract(properties, '$.weather_art_id') = ?", self.id).count
|
|
else
|
|
Ahoy::Event.where("properties::jsonb->>'event_type' = 'weather_art_view' AND (properties::jsonb->>'weather_art_id')::integer = ?", self.id).count
|
|
end
|
|
end
|
|
end
|