合并范围并在 rails 中搜索

Combine Scope and search in rails

我想将我的搜索结果与用户选择的范围结合起来。 例如,用户搜索 'Restaurant' 并单击 'Toy' link 以获得结果 Restaurant that has toy.

有人知道如何组合吗?

谢谢!

型号

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) %>

通常,表单的工作方式如下:您单击“提交”,表单中的所有值(来自输入、复选框等)将一批发送到服务器。您可以在此处阅读有关表格的更多信息: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-check_box_tag

<%= 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 %>