iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
0
自我挑戰組

Metaprogramming Ruby and Rails系列 第 28

Day 28 -- Rails 實作 Ransack 簡易搜尋及排序功能

承接上一篇 實作 Rails-i18n語言選項在Bootstrap4 導覽列,我們同樣可以
在導覽列navbar裡找到以下程式碼:

https://ithelp.ithome.com.tw/upload/images/20201013/20120868FN1W0qmQDo.png

確認導覽列安裝沒有問題後,下一步就是把 ransack gem 給它裝上去囉!

簡易設定

在你的controller裡設定如下:
https://ithelp.ithome.com.tw/upload/images/20201013/20120868tVLDkvUpNe.png

接著設定 view ( navbar.html.erb )

https://ithelp.ithome.com.tw/upload/images/20201013/20120868KgCZo0crIY.png

輸入 ‘買菜’ 測試一下是否正常運行

https://ithelp.ithome.com.tw/upload/images/20201013/201208685nmhof3NUK.png

https://ithelp.ithome.com.tw/upload/images/20201013/20120868SeXQbA3BJW.png

測試搜尋功能沒有問題,但是如果點選新增或編輯任務時會噴錯誤訊息
https://ithelp.ithome.com.tw/upload/images/20201013/20120868xMe2iAKdjI.png

錯誤訊息表示:沒有提供Ransack::Search 實體給 search_form_for
既然找不到Ransack::Search 實體,那就做出來給它吧!

解法不只一種,這裏的做法是在 application_controller.rb 裡設定Ransack::Search 的實體,以及要rails在run controller下的action前,要先跑指定的method
https://ithelp.ithome.com.tw/upload/images/20201013/20120868rVehNxJCoo.png

除了搜尋功能外,排序也是很容易做到的,在 index.html.erb 裡,照著 Ransack 提供的

sort_link 方法<%= sort_link(@q, :name) %>

依需要排序的項目做設定就可以了
https://ithelp.ithome.com.tw/upload/images/20201013/201208686UPlxhlRua.png

畫面會是這樣,可以依 ‘任務ID’ 及 ‘任務結束時間’ 來做排序

https://ithelp.ithome.com.tw/upload/images/20201013/20120868oZt6hnMkbQ.png
差不多這樣就完成了,最後要注意的是如果有用simple_form的話,記得要config/application.rb 檔內,做以下設定:(require ’rails/all’ 要放在最下面)

require File.expand_path('../boot', __FILE__)
ENV['RANSACK_FORM_BUILDER'] = '::SimpleForm::FormBuilder'
require 'rails/all'

參考資料:

使用 Ransack 幫你完成後端搜尋與 Sorting
activerecord-hackery/ransack


上一篇
Day 27 -- Rails 實作 Rails-i18n語言選項在Bootstrap4 導覽列
下一篇
Day 29 -- Stimulus with Rails 6
系列文
Metaprogramming Ruby and Rails33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0

a. 請問搜尋後網頁一片空白的話,是否是漏掉一些設置?
b. 同樣可以做出「篩選」的效果嗎?盼指點方向一二。

感謝!

我要留言

立即登入留言