Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Last active August 29, 2015 13:57
Show Gist options
  • Save rummelonp/9395322 to your computer and use it in GitHub Desktop.
Save rummelonp/9395322 to your computer and use it in GitHub Desktop.
Sunspot でタイムゾーンを考慮して投稿日を表示/投稿日毎に集計して表示

app/models/post.rb

class Post < ActiveRecord::Base
  ...
  searchable do
    time :created_at
  end
  ...
end

config/routes.rb

App::Application.routes.draw do
  ...
  get '/:blog_id/:year/:month/:day' => 'blogs#day'
  ...
end

app/controllers/blogs_controller.rb

class BlogsController < ApplicationController
  before_action :require_recent_posts_stat
  ...
  # 日毎の投稿一覧
  def day
    date = Date.new(params[:year], params[:month], params[:day])
    @posts = Post.search {
      with :blog_id, params[:blog_id]
      with :created_at, date.beginning_of_day..(date.beginning_of_day + 1.day - 1.second)
      order_by :created_at, :desc
      paginate page: params[:page], per_page: 10
    }.results
  end
  ...
  private
  # サイドバーに表示する最近の投稿一覧
  def require_recent_posts_stats
    @recent_posts_stats = Post.search {
      with :blog_id, params[:blog_id]
      facet :created_at, \
        time_range: 1.month.beginning_of_day..(Time.current.end_of_day - 1.second), \
        time_interval: 1.day
    }.facet(:created_at).rows.reverse.take(15)
  end
  ...
end

app/views/blogs/day.html.erb

...
<% @posts.each do |post| %>
  ...
  <div class="created-at updated"><%= l(post.created_at.in_time_zone) %></div>
  ...
<% end %>
...

app/views/blogs/_sidebar.html.erb

...
<% @recent_posts_stats.each |stat| %>
  <% date = stat.value.first.in_time_zone.to_date %>
  <p><%= link_to("#{l(date)} (#{stat.count})", day_path(params[:blog_id], date.year, date.month, date.day)) %></p>
<% end %>
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment