Rails filterrifi c не обновляет вид после выбора фильтра - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь добавить filterrifi c в мое приложение rails. Я следовал этому учебнику, но мое живое обновление не работает. Мне нужно нажать refre sh, чтобы обновить результаты, на мой взгляд. Я пытался найти решение и нашел несколько ссылок ( Ссылка 1 , Ссылка 2 ), но безуспешно. Ниже приведен мой код.

agent.rb

class Agent < ApplicationRecord
  STATUS_ACTIVE = 'ACTIVE'.freeze
  STATUS_INACTIVE = 'INACTIVE'.freeze

  filterrific(
      default_filter_params: { sorted_by: 'name_asc' },
      available_filters: [
          :sorted_by,
          :search_query,
          :with_agent_id,
      ]
  )

  scope :sorted_by, lambda { |sort_option|
    direction = /desc$/.match?(sort_option) ? "desc" : "asc"
    case sort_option.to_s
    when /^name/
      order("name #{direction}")
    when /^location/
      order("location #{direction}")
    else
      raise(ArgumentError, "Invalid sort option: #{sort_option.inspect}")
    end
  }
  scope :search_query, lambda { |query|
    # Filters students whose name or email matches the query
  }
  scope :with_agent_id, lambda { |agent_ids|
    where(id: agent_ids)
  }

  # This method provides select options for the `sorted_by` filter select input.
  # It is called in the controller as part of `initialize_filterrific`.
  def self.options_for_sorted_by
    [
        ["Name (a-z)", "name_asc"],
        ["Name (z-a)", "name_desc"],
        ["Location (a-z)", "location_asc"],
    ]
  end
end

AgentsController / index. html .erb

def index
    @filterrific = initialize_filterrific(
        Agent,
        params[:filterrific],
        select_options: {
            sorted_by: Agent.options_for_sorted_by,
        },
        persistence_id: true,
        default_filter_params: {},
        available_filters: [:sorted_by],
        sanitize_params: true,
        ) || return

    @agents = @filterrific.find.paginate(page: params[:page], per_page: 10)
  end

index. html .erb

<%= form_for_filterrific @filterrific do |f| %>
  <div>
    Search
    <%= f.text_field(
            :search_query,
            class: 'filterrific-periodically-observed'
        ) %>
  </div>
  <div>
    Sorted by
    <%= f.select(:sorted_by, @filterrific.select_options[:sorted_by]) %>
  </div>
  <div>
    <%= link_to(
            'Reset filters',
            reset_filterrific_url,
            ) %>
  </div>
  <%# add an automated spinner to your form when the list is refreshed %>
  <%= render_filterrific_spinner %>
<% end %>

<%= render(
        partial: 'agents/list',
        locals: { agents: @agents }
    ) %>

_list. html .erb (частично)

<div id="filterrific_results">
  <table class="table">
    <thead>
    <tr>
      <th><%= filterrific_sorting_link(@filterrific, :name) %></th>
      <th><%= filterrific_sorting_link(@filterrific, :location) %></th>
    </tr>
    </thead>

    <tbody>
    <% agents.each do |agent| %>
      <tr>
        <td><%= agent.name %></td>
        <td><%= agent.location %></td>
      </tr>
    <% end %>
    </tbody>
  </table>
</div>

<%= will_paginate agents %>

logs

Started GET "/agents?filterrific%5Bsorted_by%5D=location_desc" for ::1 at 2020-03-12 16:26:07 +0530
Processing by AgentsController#index as JS
  Parameters: {"filterrific"=>{"sorted_by"=>"location_desc"}}
  User Load (301.8ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 5], ["LIMIT", 1]]
  ↳ app/controllers/agents_controller.rb:107:in `authenticate_user'
  Rendering agents/index.js.erb
  Agent Load (248.2ms)  SELECT "agents".* FROM "agents" ORDER BY location desc LIMIT $1 OFFSET $2  [["LIMIT", 10], ["OFFSET", 0]]
  ↳ app/views/agents/_list.html.erb:20
  Rendered agents/_list.html.erb (Duration: 255.6ms | Allocations: 1562)
  Rendered agents/index.js.erb (Duration: 268.5ms | Allocations: 5750)
Completed 200 OK in 585ms (Views: 27.3ms | ActiveRecord: 550.0ms | Allocations: 8947)

1 Ответ

1 голос
/ 06 марта 2020

Я думаю, вам нужно добавить javascript, чтобы в режиме реального времени обновлять свой результат. Можете ли вы добавить следующий код как index.js.erb вместе с index.html.erb

<% js = escape_javascript(
  render(partial: agents/list, locals: { agents: @agents })
) %>
$("#filterrific_results").html("<%= js %>");

...