1

我正在使用 ransack 提前搜索我的一个项目。我面临一个问题,如果我进行搜索并保存查询,我将无法使用这些查询再次重建搜索表单。我正在寻找的是,当我进行搜索时,我应该能够再次看到相同的表单,其中包含相同的值。

布局/_search.html.erb

<%= search_form_for @search, url: url, method: :post, class: search_form_class, remote: true do |f| %>
    <%= f.condition_fields do |c| %>
    <%= render "layouts/condition_fields", f: c %>
  <% end %>
  <%= f.submit %>
<% end %>

布局/_condition_fields.html.erb

<div class="field">
  <%= f.attribute_fields do |a| %>
    <%= a.attribute_select %>
  <% end %>
  <%= f.predicate_select %>
  <%= f.value_fields do |v| %>
    <%= v.text_field :value %>
  <% end %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</div>

people_controllers.rb

  def index
    @search = Person.ransack(params[:q])
    @people = @search.result(distinct: true)
    @search.build_condition
    respond_to do |format|
      format.html
    end
  end

人/index.html.erb

<%= render :partial => 'layouts/search', :locals => {:search => @search, :url => search_people_path, search_form_class: 'all_person'} %>
<div class="searchResult">
    <%= render :partial => 'layouts/search_result', :locals => {:People => @people} %>

布局/_search_result.html.erb

<div class="box">
    <div class="box-body">
        <table class="table table-bordered">
            <tbody>
                <tr>
                    <th>id</th>
                    <th>name</th>
                    <th>email</th>
                </tr>
                <% @people.each do  |person|  %>
                    <tr>
                        <td>
                            <%= person.id %>
                        </td>
                        <td>
                            <%= person.name %>
                        </td>
                        <td>
                            <%= person.email %>
                        </td>
                    </tr>
                <% end %>
            </tbody>

    </table>    
    </div>
</div>

这就是现在当我去查看时它出现的地方。

提前搜查

看起来有人 在这里问类似的问题!

我完全想要同样的东西。

  1. 如何保存表单搜索值并保存这些详细信息以供以后查询
  2. 通过采用现有查询生成表单来编辑保存的查询
4

2 回答 2

1

对于那些将来阅读本文的人:您可以使用这些params[:q]值的存在(如果有)将默认值应用于您的搜索字段。这有点hacky,但它非常简单,可以满足您的需求。

这是一些可以满足您需求的东西:

<div class="form-group">
    <%= f.label :person_name_cont %>
    <% if params[:q] && params[:q][:person_name_cont]  %>
      <%= f.select :person_name_cont, Person.all.map(:name), {:include_blank => true, :selected => params[:q][:person_name_cont]} %>
    <% else %>
      <%= f.select :person_name_cont, Person.all.map(:name), {:include_blank => true} %>
    <% end %>
  </div>
于 2020-08-03T04:09:30.613 回答
0

据我了解,您想将此查询另存为,favorite因此您应该创建一个favorite模型

rails g model favorite url:string

您正在执行的查询作为获取请求在 url 上传递。

例如http://localhost:3000/peoples?page=2&sort=newest&pagesize=15

此查询正在使用参数get对 url执行请求http://localhost:3000/people

people[:page] = 2
people[:sort] = newest
....

您可以在页面上包含星形图标并执行此处所述的 ajax 请求,这将触发favorites#create操作

def create
    Favorite.create(favorite_params)
end
于 2018-01-30T11:38:39.440 回答