简体   繁体   中英

How to create a form using simple_form to control scopes (via has_scope) in a view

Basically, I cannot figure out how to prevent the form generator from encapsulating everything in a hash (filter{...}), thus making it easy for the form to set the params used in the view's scoping.

has_scope code in controller:

has_scope :degree_id
has_scope :discipline_id
has_scope :competency_id
has_scope :type_id
has_scope :year

simple_form code in view:

<%= 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 %>

Sample output URL:

.../analyze/school?utf8=✓&filter%5By%5D=2016&filter%5Bdiscipline_id%5D=2&filter%5Bcompetency_id%5D=2&filter%5Btype_id%5D=1&commit=Filter

Desired output URL:

.../analyze/school?y=2016&discipline_id=2&competency_id=2&type_id=1

1st Solution: Just iterate over the hash and set the params used by scope.

(+) This works and is fairly simple (-) The URL is still messy (-) This seems hacky

params[:filter].each do |k,v|
   params[k] = v
end

Solution 2: Create the form using pure HTML.

(+) URL info is cleaner (-) Code is messier and brittler (-) This seems hacky

I've Googled a lot and am surprised that I've not come across something that makes it easy to create forms in conjunction with has_scope.

Please save me from having to use one of the above solutions! Thanks!

I think you could use the simple form_tag by rails:

See more about that here: http://guides.rubyonrails.org/form_helpers.html

Or just implement a method like

def parse_filter_params
  params.merge!(params[:filter]) if params[:filter]
end

and apply it before each action you want:

before_action :parse_filter_params

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM