LoginSignup
4
0

More than 5 years have passed since last update.

Railsで曜日検索をする

Posted at

Railsで曜日検索を行う

下記のようなチェックボックスでupdate_atでの曜日検索機能を実装したのでメモ。
もっといい方法がありましたらコメントにて教えていただけますと幸いです。

スクリーンショット 2018-01-04 23.37.16.png

環境

Rails 5.0.3
Ruby 2.4.0
SqlLite3 1.3.13

index.html.erb
<label class="weekday">曜日</label>
<div class="checkbox">
    <% @weekdays.each_with_index do |weekday, i| %>
        <label><%= check_box_tag 'condition[weekdays][]', i, @weekdays_index.include?(i.to_s), id:"condition_weekdays_#{i}"  %><%= weekday %></label>
    <% end %>
</div>
users_controller.rb
def index
  @weekdays = %w[日 月 火 水 木 金 土]
  @weekdays_index = ['0','1','2','3','4','5','6']
  @user = Search::User.new

  unless params[:condition].nil?
    @weekdays_index = params[:condition][:weekdays]
  end

  @users = @user
    .matches(@weekdays_index)
end
user.rb
class Search::User < Search::Base
  def matches(cwdays)
    t = ::User.arel_table
    results = ::User.all
    results = results.where(%(strftime('%w', update_at) in (?)), cwdays)
    results
  end
end
4
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0