在rails中结合作用域和搜索

fnx2tebb  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(291)

我想结合我的搜索结果与用户选择的范围。例如,用户搜索'餐厅'并点击'玩具'链接,得到一个结果餐厅,有玩具。
有人知道怎么组合吗?
谢谢!
模型

scope :filter_by_toy, -> { where(toy: true) }
scope :filter_by_play_area, -> { where(play_area: true) }

控制器

def index
  @places = policy_scope(Place)
  @places = Place.all
  @places = Place.global_search(params[:query]) unless params[:query].blank?

  #scope filtering
  if params[:toy]
    @places = @places.filter_by_toy
  end

if params[:play_area]
    @places = @places.filter_by_play_area
  end
end

看法

<%= form_for :search, url: places_path, class: "search-form", method: :get do %>
  <div class="search-box">
      <%= text_field_tag :query, params[:query],
        class: "search-input placeholder-search",
        placeholder: "City, place name, type..."%>
      <button type="submit" class="search-submit"><i class="fas fa-search"></i></button>
  </div>
<% end %>

<%= link_to 'Toy', places_path(:toy => true) %>
<%= link_to 'Play Area', places_path(:play_area => true) %>
mbyulnm0

mbyulnm01#

通常,表单是这样工作的:单击“submit”,表单中的所有值(来自输入、复选框等)将一批发送到服务器。您可以在此处阅读有关表单的更多信息:https://developer.mozilla.org/en-us/docs/web/html/element/form
特别针对您的问题,您可以使用 check_box_tag 把它们移到表格里。查看更多:https://api.rubyonrails.org/classes/actionview/helpers/formtaghelper.html#method-i-复选框标记

<%= form_for :search, url: places_path, class: "search-form", method: :get do %>
  <div class="search-box">
      <%= text_field_tag :query, params[:query],
        class: "search-input placeholder-search",
        placeholder: "City, place name, type..."%>
      <%= check_box_tag "toy" %>
      <%= check_box_tag "play_area" %>
      <button type="submit" class="search-submit"><i class="fas fa-search"></i></button>
  </div>
<% end %>

相关问题