【问题标题】:Ransack showing all instead of filterRansack 显示全部而不是过滤器
【发布时间】:2018-02-04 06:53:16
【问题描述】:

我正在尝试使用 Ransack gem,但它返回所有 12,000 行而不是使用过滤器。

控制器:

	def list
		@q = LmiHost.ransack(params[:q])
		if !(params[:commit].nil?) then
			@computers = @q.result
		else
			@computers = LmiHost.where(:job_id => 121)
		end
	end

查看:

<script type="text/javascript">
	$(document).ready(function() {
  $("#computer_search_results").dataTable();
});
</script>

<table id="computer_search_table">
	<%= search_form_for @q do |f| %>
	<tr><td>Project:</td><td><%= f.select :job_id, @project_job_selector %></td></tr>
	<tr><td><%= f.submit 'Search' %></td></tr>
	<%end%>
</table>


<table id="computer_search_results">
	<thead>
		<tr>
			<th>Lmi Name</th>
			<th>Service Tag</th>
			<th>Model</th>
			<th>Ship Date</th>
			<th>Warranty Date</th>
			<th>Project</th>
			<th>Invoice Name</th>
		</tr>
	</thead>
	<tbody>
		<% @computers.each do |computer| %>
		<tr>
			<td><%= computer.host_description %></td>
			<td><%= computer.host_service_tag %></td>
			<td><%= computer.host_model %></td>
			<td><%= computer.ship_date %></td>
			<td><%= computer.warranty_date %></td>
			<td><%= computer.job.name unless computer.job.nil? %></td>
			<td><%= computer.invoice_name %></td>
		</tr>
		<% end %>
	</tbody>
</table>

搜索后 URL 看起来没问题: URL

但它的行为就像:

@computers = LmiHost.all

关于为什么会发生这种情况的任何想法?

【问题讨论】:

  • 你在日志中的参数是什么样子的?
  • 在 2018-02-03 23:26:12 -0800 开始 GET "/computer/list?utf8=%E2%9C%93&q%5Bjob_id%5D=1726&commit=Search" 为 127.0.0.1由 ComputerController#list 处理为 HTML 参数:{"utf8"=>"✓", "q"=>{"job_id"=>"1726"}, "commit"=>"Search"}
  • 对我来说似乎没问题。为什么不在列表中添加一个 'byebug' 并使用 params[:q] 和 @q.result 进行调试,看看那里到底发生了什么。
  • (byebug) @q Ransack::Search> (byebug) @q.result #<:relation id:> (byebug) @q.result.count CACHE (0.0ms) SELECT COUNT(*) FROM lmi_hosts 12600 (byebug)
  • @q.result的时候看不到它生成的sql语句吗?你可以看到那里发生了什么并找出问题所在

标签: ruby-on-rails ransack


【解决方案1】:

你做错的是你没有指定一个合适的匹配器。如果您想选择特定的工作 ID,您应该在表格中指明搜索匹配器。

例如,您说 job_id 应该是 job_id_eq 或者您希望它是什么匹配器

您应该在哪里获取 Ransack Search 项目,如下所示。

Ransack::Search<class: LmiHost, base: Grouping <conditions: [Condition <attributes: ["job_id"], predicate: eq, values: ["123"]>], combinator: and>> 

在您的 Ransack 搜索中,我没有看到谓词,因此它返回所有结果。

【讨论】:

  • 我花了一段时间才弄清楚这个答案的含义。更详细地说,在视图中,job_id 应该重命名为job_id_eq,其中eq 是此处指定的匹配器之一github.com/activerecord-hackery/ransack#search-matchers。如果要匹配包含某个值的文本,请在视图中使用 job_description_cont 而不是 job_description。
猜你喜欢
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多