【问题标题】:Combine Scope and search in rails在 Rails 中结合范围和搜索
【发布时间】:2020-10-11 09:57:21
【问题描述】:

我想将我的搜索结果与用户选择的范围相结合。 例如,用户搜索“Restaurant”并单击“Toy”链接以获取包含玩具的结果 Restaurant。

有人知道如何组合吗?

谢谢!

型号

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

【问题讨论】:

  • 您的解决方案有什么问题?在我看来没问题。编辑:哦,你的意思是结合视图上的查询,而不是控制器上的结果。我明白了。
  • 您使用哪个库进行搜索?
  • 将所有过滤器(链接)作为选择框的选项包含在表单上,​​而不是使用单独的链接不是更好吗?你的 UI 对我来说没有多大意义。
  • @ChristianBruckmayer 我使用 pg_search

标签: sql ruby-on-rails ruby scope


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 2014-10-09
    • 2014-11-18
    相关资源
    最近更新 更多