flchp 关注 2023-08-15 112 31 23 22
模糊搜索是网站的一个非常常见的功能。
1 | +gem 'ransack'
|
执行$ bundle install,重启服务器
修改controller
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 |
添加搜索框
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> |
完成
