diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 0c12e79..dc0ae62 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -1,7 +1,8 @@ class HomeController < ApplicationController def index - @popular_shuffle_arts = WeatherArt.by_popularity(10).shuffle.last(6) - @latest_arts = WeatherArt.latest(12) + @popular_arts = WeatherArt.by_popularity(3) + @random_arts = WeatherArt.random(3) + @latest_arts = WeatherArt.latest(6) @featured_arts = WeatherArt.includes(:city).order(created_at: :desc).limit(5) set_meta_tags( title: "AI-Generated Weather Art", diff --git a/app/models/weather_art.rb b/app/models/weather_art.rb index 344fe8b..175b7c4 100644 --- a/app/models/weather_art.rb +++ b/app/models/weather_art.rb @@ -31,6 +31,19 @@ class WeatherArt < ApplicationRecord end } + scope :random, ->(limit = 3) { + if ActiveRecord::Base.connection.adapter_name.downcase == "postgresql" + # PostgreSQL 优化版本 + order(Arel.sql('RANDOM()')).limit(limit) + elsif ActiveRecord::Base.connection.adapter_name.downcase == "mysql2" + # MySQL 优化版本 + order(Arel.sql('RAND()')).limit(limit) + else + # SQLite 或其他数据库的通用版本 + order(Arel.sql('RANDOM()')).limit(limit) + end + } + def should_generate_new_friendly_id? weather_date_changed? || city_id_changed? || super end diff --git a/app/views/home/_arts.html.erb b/app/views/home/_arts.html.erb new file mode 100644 index 0000000..63f0c3c --- /dev/null +++ b/app/views/home/_arts.html.erb @@ -0,0 +1,29 @@ +
+ <% arts.each do |art| %> +
+
+ <% if art.image.attached? %> + <%= image_tag art.image, class: "w-full h-full object-cover transform hover:scale-105 transition-transform duration-500" %> + <% end %> +
+
+
+
+

<%= art.city.name %>

+

+ <%= art.weather_date.strftime("%B %d, %Y") %> +

+
+
+
<%= art.temperature %>°C
+
<%= art.description %>
+
+
+
+ <%= link_to "View Details", city_weather_art_path(art.city, art), + class: "btn btn-primary btn-outline" %> +
+
+
+ <% end %> +
\ No newline at end of file diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb index 36c1e16..b50e835 100644 --- a/app/views/home/index.html.erb +++ b/app/views/home/index.html.erb @@ -25,37 +25,12 @@
-

Shuffle Latest Weather Art

- -
- <% @latest_arts.each do |art| %> -
-
- <% if art.image.attached? %> - <%= image_tag art.image, class: "w-full h-full object-cover transform hover:scale-105 transition-transform duration-500" %> - <% end %> -
-
-
-
-

<%= art.city.name %>

-

- <%= art.weather_date.strftime("%B %d, %Y") %> -

-
-
-
<%= art.temperature %>°C
-
<%= art.description %>
-
-
-
- <%= link_to "View Details", city_weather_art_path(art.city, art), - class: "btn btn-primary btn-outline" %> -
-
-
- <% end %> -
+

Latest Weather Art

+ <%= render 'home/arts', arts: @latest_arts %> +

Popular Weather Art

+ <%= render 'home/arts', arts: @popular_arts %> +

Random Weather Art

+ <%= render 'home/arts', arts: @random_arts %>