【发布时间】:2018-09-11 17:04:17
【问题描述】:
我正在尝试使用表单搜索 MongoDB 集合。我想做的是使用 Ajax 动态更新我的结果,而不必在每次提交搜索表单后刷新页面。我如何在 Rails 中解决这个问题?
scenarios_controller:
class ScenariosController < ApplicationController
before_action :set_scenario, only: [:edit, :update]
before_action :all_scenarios, only: [:index, :create, :update]
respond_to :html, :js
def index
@scenarios = if params[:submitter].blank? && params[:application].blank? && params[:pillar].blank? && params[:test_type].blank? && params[:begin_date].blank? && params[:end_date].blank? && params[:search_text].blank?
Scenario.all.order_by(created_at: :desc)
else
Scenario.search_text(params)
end
end
index.html.erb:
...
<div id="search_form_class">
<%= render 'search_form', remote: true %>
</div>
<div id="results_class">
<%= render 'results', remote: true %>
</div>
...
_search_form.html.erb:
<%= form_tag(scenarios_path, remote: true, method: 'get', id: 'search-form', role: 'form') do %>
<%= select_tag :submitter, include_blank: true, class: "form-control" %>
<%= select_tag :application, include_blank: true, class: "form-control" %>
...
<% end %>
_search_form.js.erb:
$('#search-form').html("<%= j (render 'search_form', scenario: @scenario) %>")
_results.html.erb:
<table class="table table-striped" style="max-height: 800px; overflow:scroll;">
<thead>
<tr>
<th>Export?</th>
<th>Submitter</th>
<th>Scenario Name</th>
<th>Scenario Body</th>
<th>Created</th>
<th>Modified</th>
<th>Test Type</th>
<th>Application</th>
<th>Pillar</th>
<th>Options</th>
<th colspan="8"></th>
</tr>
</thead>
<tbody>
<% @scenarios.each do |scenario| %>
<tr>
<td class="text-left"><%= check_box_tag('compare') %></td>
<td class="text-left"><%= scenario.submitter %></td>
<td class="text-left"><%= scenario.scenario_name %></td>
<td class="text-left"><%= scenario.scenario_body %></td>
<td class="text-left"><%= scenario.created_at %></td>
<td class="text-left"><%= scenario.updated_at %></td>
<td class="text-left"><%= scenario.test_type %></td>
<td class="text-left"><%= scenario.application %></td>
<td class="text-left"><%= scenario.pillar %></td>
<td><%= render 'options', scenario: scenario %></td>
</tr>
<% end %>
</tbody>
</table>
【问题讨论】:
标签: ruby-on-rails ajax ruby-on-rails-5