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