基本上,我不知道如何防止表单生成器将所有内容封装在哈希中(filter{…}),从而使表单可以轻松设置视图作用域中使用的参数。
控制器中的has_scope代码:
has_scope :degree_id
has_scope :discipline_id
has_scope :competency_id
has_scope :type_id
has_scope :year
视图中的simple_form代码:
<%= simple_form_for :filter, url: analyze_school_path, method: :get do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :y, label: 'Year', collection: @years, include_blank: '- Year -' %>
<%= f.input :discpline_id, label: 'Discipline', collection: Discipline.all, include_blank: '- Discipline -' %>
<%= f.input :competency_id, label: 'Competency', collection: Competency.all, include_blank: '- Competency -' %>
<%= f.input :type_id, label: 'Type', collection: JobType.all, include_blank: '- Type -' %>
</div>
<div class="form-actions">
<%= f.button :submit, 'Filter', class: "btn btn-primary" %>
</div>
<% end %>
示例输出URL:
/分析/学校?utf8=✓&过滤器%5By%5D=2016&筛选器%5规程_id%5D=2&筛选器%5Competency_id%5D=2&筛选器%5Btype_id%5D=1&commit=过滤
所需输出URL:
/分析/学校?y=2016&ind=2&competency_ id=2&type_id=1
第一个解决方案:只需迭代哈希并设置scope使用的参数。
(+)这很有效,也很简单(-)URL仍然很乱(-)这似乎是一个黑客
params[:filter].each do |k,v|
params[k] = v
end
解决方案2:使用纯HTML创建表单。
(+)URL信息更干净(-)代码越来越混乱(-)这似乎是一个黑客
我在谷歌上搜索了很多,很惊讶我没有发现可以轻松地与has_scope一起创建表单的东西。
请不要让我不得不使用上述解决方案之一!谢谢
我认为您可以通过rails使用简单的form_tag:
点击此处查看更多信息:http://guides.rubyonrails.org/form_helpers.html
或者只是实现一种类似的方法
def parse_filter_params
params.merge!(params[:filter]) if params[:filter]
end
并在你想要的每个动作之前应用它:
before_action :parse_filter_params