activeadmin_active_resource
activeadmin_active_resource copied to clipboard
Filter support
Thanks for this gem! I managed to make the filters form preserve its state after the submit and also render "Search status" sidebar content.
class Test < ActiveResource::Base
class << self
RansackContextStub = Struct.new(:class_name) do
def bind(attr, attr_name)
attr.attr_name = attr_name
attr.parent = class_name
end
def klassify(parent)
parent.constantize
end
def type_for(attr)
klassify(attr.parent).schema.fetch(attr.name)
end
def present?
false
end
def lock_association(*) end
def auth_object; end
end
def ransack_context
@ransack_context ||= RansackContextStub.new(name)
end
def _ransackers
values =
schema.map do |k, v|
Struct.new(:name, :type) do
def attr_from(_bindable)
name # not sure what to return, but it's probably not used anyway
end
end.new(k, v)
end
schema.keys.zip(values).to_h
end
def ransackable_attributes(*)
schema.keys
end
def ransack(params = {}, _options = {})
@ransack_params = params.blank? ? {} : params.permit!.to_h
conditions = @ransack_params.map { |k, v| Ransack::Nodes::Condition.extract(ransack_context, k, v) }
result = OpenStruct.new(conditions: conditions, object: OpenStruct.new(klass: self), result: self)
@ransack_params.each { |k, v| result[k] = v }
result.instance_variable_set '@scope_args', []
result
end
end
end
@AlexanderPavlenko Thanks for the code, it put this code in my model 'Report' but I am getting an error below:
undefined method `base_klass' for "Report":String
I have managed to write a javascript code to preserve the filters on page refresh.
document.addEventListener("DOMContentLoaded", function(event) {
const form = document.getElementById("new_q");
//If the page is loaded with the filter operation, apply the saved filters in the filters form.
if(form){
url = new URL(window.location.href);
restoreFilterData = {} ;
storageKey = `FormFilterData_${url.pathname}`; // To save filter for the appropriate end point.
if(url.search)
restoreFilterData = JSON.parse(localStorage.getItem(storageKey));
for (const key in restoreFilterData) {
if (restoreFilterData.hasOwnProperty(key)) {
element = form.elements[key];
if (element)
element.value = restoreFilterData[key];
}
}
form.addEventListener("submit", function(event) {
// Prevent the default form submission
event.preventDefault();
saveFilterData = {};
for (const element of form.elements)
if (element.id)
saveFilterData[element.id] = element.value;
saveFilterData = JSON.stringify(saveFilterData)
//Store the filter data in SessionStorate
localStorage.setItem(storageKey, saveFilterData);
// Proceed with the form submission
form.submit();
});
}
})