我正在更新具有ActiveAdmin组件(ActiveAdmin 0.6,Ruby 1.9.3和Rails 3.2)的旧ruby \ rails应用程序。用户已经请求过滤器来搜索给定模型中的所有字段。我不认为这是实际的,因为你不能搜索日期或数字值“a”,所以我已经妥协了只用过滤器搜索文本。ActiveAdmin从动态模型属性中自定义过滤器
查看了ActiveAdmin文档后,您可以使用属性之间的“或”创建多个属性的过滤器。所以,如果我想搜索“情况”或“accident_type”属性,我会使用下面的过滤:如果我用这个语法过滤器工作正常
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以上?也就是说,您是否在寻找一种搜索或元搜索解决方案? – ahmacleod
不,我不想更新ActiveAdmin。我正在寻找一种解决方案,可以让我随时构建垃圾过滤器。 –