Ruby on rails 在RubyonRails中排序后保留搜索结果
我正在尝试建立一个可排序和可搜索的列表 这两个函数都独立工作,但当我搜索并尝试对结果进行排序时,我会再次获取所有元素,而不仅仅是搜索到的元素 我的观点如下:Ruby on rails 在RubyonRails中排序后保留搜索结果,ruby-on-rails,Ruby On Rails,我正在尝试建立一个可排序和可搜索的列表 这两个函数都独立工作,但当我搜索并尝试对结果进行排序时,我会再次获取所有元素,而不仅仅是搜索到的元素 我的观点如下: <%= form_tag(user_subnets_path, :method => "get", id: "search-form") do %> <%= text_field_tag :search, params[:search], placeholder: "Search Subnets" %>
<%= form_tag(user_subnets_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Subnets" %>
<%= submit_tag "Search" %>
<% end %>
<% if @subnets.blank? and params[:search]%>
<h4>There are no subnets containing the term "<%= params[:search] %>".</h4>
<% else %>
<table>
<tr>
<th><%= sortable "name" %></th>
<th><%= sortable "CIDR", "CIDR" %></th>
</tr>
<% @subnets.each do |subnet| %>
<tr>
<td><%= subnet.name %></td>
<td><%= subnet.CIDR %></td>
<td><%= link_to 'Show', user_subnet_path(@user, subnet) %></td>
<td><%= link_to 'Edit', edit_user_subnet_path(@user, subnet) %></td>
</tr>
<% end %>
</table>
<% end %>
以及模型中的搜索
功能
def self.search(search)
if search
where("subnets.name LIKE ? OR subnets.CIDR LIKE ?", "%#{search}%", "%#{search}%")
else
all
end
end
以及应用程序\u助手
module ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc"
link_to title, :sort => column, :direction => direction
end
end
有没有一个简单的方法可以做到这一点
我正在运行Rails 5.1.4
提前谢谢 似乎还可以,现在所有的都很好,只是对应用程序帮助程序的
排序方法和最后一行做了一些小的更改
尝试以下方法
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc"
link_to title, request.query_parameters.merge({sort: column, direction: direction})
end
希望对您有所帮助请发布您的助手类,其中来自sortable
come我添加了application\u helper
code在索引操作中调用搜索方法后尝试应用order方法
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc"
link_to title, request.query_parameters.merge({sort: column, direction: direction})
end