这是我的搜索模型:
filterrific(
default_filter_params: { sorted_by: 'created_at_desc' },
available_filters: [
:sorted_by,
]
)
scope :sorted_by, lambda { |sort_option|
# extract the sort direction from the param value.
direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
case sort_option.to_s
when /^created_at_/
# Simple sort on the created_at column.
# Make sure to include the table name to avoid ambiguous column names.
# Joining on other tables is quite common in Filterrific, and almost
# every ActiveRecord table has a 'created_at' column.
order("searches.created_at #{ direction }")
else
raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
end
}
def self.options_for_sorted_by
[
['Created at (Newest first)', 'created_at_desc'],
['Created at (Oldest first)', 'created_at_asc']
]
end
这是我的搜索控制器:
def index
@filterrific = initialize_filterrific(
Search,
params[:filterrific],
select_options: {
sorted_by: Search.options_for_sorted_by
},
persistence_id: 'shared_key',
default_filter_params: {},
available_filters: [],
) or return
@searches = @filterrific.find.paginate(page: params[:page], per_page: 5)
respond_to do |format|
format.html
format.js
end
end
这是我的index.html.erb:
<%= form_for_filterrific @filterrific do |f| %>
<div>
Sorted by
<%= f.select(:sorted_by, @filterrific.select_options[:sorted_by]) %>
</div>
<div>
<%= link_to(
'Reset filters',
reset_filterrific_url,
) %>
</div>
<%= render_filterrific_spinner %>
<% end %>
<%= render 'searches/search', locals: { searches: @searches } %>
这是我的部分_search.html.erb:
<div id="filterrific_results">
<% @searches.each do |search| %>
<%= time_ago_in_words(search.created_at) %>
...
<% end %>
</div>
<%= will_paginate @searches %>
最后,我的index.js.erb:
<% js = escape_javascript(
render(partial: 'searches/search', locals: { searches: @searches })
) %>
$("#filterrific_results").html("<%= js %>");
为什么我觉得接近解决方案? 从&#39; created_at_desc&#39;更改default_filter_params到&#39; created_at_asc&#39;工作中。此外,选项选择列表也会自动更改为在(最早的第一个)创建的&#39;。但是当我更改选项时,选择什么都不会发生,除了微调器显示一秒钟。
感谢您的帮助!
答案 0 :(得分:0)
我自己就找到了解决方案。我将:sorted_by
添加到搜索控制器。