我正在尝试构建一个可排序且可搜索的列表。
这两个函数都可以自行运行,但是当我搜索并尝试对结果进行排序时,我会再次获取所有元素,而不仅仅是搜索到的元素。
我的观点如下:
<%= 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 index
#TODO: keep params after submit -> Search + order at once
@user = User.find(params[:user_id])
@subnets = @user.subnets.order(sort_column+ ' ' +sort_direction).search(params[:search])
respond_to do |format|
format.html
format.csv { send_data Subnet.to_csv(@subnets) }
end
end
...
private
def subnet_params
params.require(:subnet).permit(:name, :CIDR)
end
def sort_column
if params[:id]
Device.column_names.include?(params[:sort]) ? params[:sort] : "IP"
else
Subnet.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
来自模型的search
函数
def self.search(search)
if search
where("subnets.name LIKE ? OR subnets.CIDR LIKE ?", "%#{search}%", "%#{search}%")
else
all
end
end
application_helper
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
提前致谢!
答案 0 :(得分:1)
似乎没关系,现在只需对应用程序助手sortable
方法和最后一行进行少许更改
尝试以下
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
希望有所帮助