【发布时间】:2015-10-06 09:05:33
【问题描述】:
我正在更新具有 ActiveAdmin 组件(ActiveAdmin 0.6、Ruby 1.9.3 和 Rails 3.2)的旧 ruby\rails 应用程序。用户请求了一个过滤器来搜索给定模型中的所有字段。我认为这不切实际,因为您无法搜索“a”的日期或数值,因此我在仅使用过滤器搜索文本方面做出了妥协。
查看了 ActiveAdmin 文档,这表明您可以在属性之间使用“或”为多个属性创建过滤器。因此,如果我想搜索“情况”或“事故类型”属性,我会使用下面的过滤器:
filter :circumstances_or_accident_type, :as => :string, label: "Search All Text Fields"
如果我使用这种语法,过滤器会按预期工作。
我现在想通过我使用此代码所做的过滤器属性找到要创建的所有字符串\文本属性(可能有更简洁的方法,但它有效):
xfilter_text = ""
Notification.columns.each do |xfield|
if xfield.type == :string or xfield.type == :text
if xfilter_text.length == 0
xfilter_text = xfield.name
else
xfilter_text << "_or_"
xfilter_text << xfield.name
end
end
end
我使用结果将值硬编码到过滤器中,这给了我以下信息(是的,模型中有一些属性):
filter :circumstances_or_accident_type_or_author_type_or_location_or_immediate_action_or_injury_details_or_outcome_type_or_investigation_findings_or_action_to_prevent_recurrence_or_building_or_classification_or_manager_email_or_manager_name_or_current_stage_or_injured_last_name_or_injured_first_name_or_injured_gender_or_injured_address_or_injured_home_telephone_or_injured_work_status_or_injured_job_title_or_injured_working_pattern_or_injured_email_or_riddor_document_or_body_part_or_kind_of_accident_or_injury_type_or_service_or_team_or_defects_or_witness_details_or_location_details_or_hse_reference_number_or_riddor_category_or_address_or_details_of_treatment_or_processor_actions_or_business_unit_or_other_author_type_or_lost_time_details_or_changed_by_or_details_of_hospital_treatment, :as => :string, label: "Search All Text Fields"
我对此进行了测试,它确实有效。到目前为止一切都很好。我可以把它留在这里,但我想确保代码是自我维护的,因此模型中的任何更改都不需要更改自定义过滤器。这是我遇到麻烦的部分。我想更改硬编码属性以使用以某种方式创建过滤器属性的代码结果。像这样的:
filter :get_filter, :as => :string, label: "Search All Text Fields"
def get_filter
xfilter_text = ""
Notification.columns.each do |xfield|
if xfield.type == :string or xfield.type == :text
if xfilter_text.length == 0
xfilter_text = xfield.name
else
xfilter_text << "_or_"
xfilter_text << xfield.name
end
end
return xfilter
end
end
我希望我需要一些东西来检查是否返回了属性,否则过滤器会失败。一旦我让代码工作,我可以添加它。
感谢任何帮助或建议。
【问题讨论】:
-
您是否将 ActiveAdmin 更新到 0.6 以上?即,您是否在寻找洗劫或元搜索解决方案?
-
不,我不想更新 ActiveAdmin。我正在寻找一种解决方案,让我可以即时构建 ransack 过滤器。