用Ransack给博客添加一个搜索功能

flchp 关注2023-08-15112312322


模糊搜索是网站的一个非常常见的功能。

安装gem

gemfile
1
+gem 'ransack'

执行$ bundle install,重启服务器

使用

修改controller

app/controllers/account/posts_controller.rb
1
2
3
4
5
6
7
8
   def index
-    @posts = current_user.posts.order("created_at DESC")
+
+    @q = current_user.posts.ransack(params[:q])
+    @posts = @q.result.order("created_at DESC")
+
     @this_year = nil
   end

添加搜索框

app/views/account/posts/index.html.erb
1
2
3
4
5
6
7
8
9
10
11
+
+  <div class="col-6 mx-auto my-2 ">
+  <%= search_form_for [:account, @q] do |f|  %>
+    <div class="d-flex">
+      <%= f.search_field :title_or_content_cont, class: "form-control", placeholder: "输入搜索关键字",  autocomplete: "off"  %>
+      <%= f.submit "搜索", class: "btn btn-outline-success", style: "width: 80px"%>
+    </div>
+  <% end %>
+  </div>

完成


上一篇 返回目录 下一篇