简体   繁体   中英

Linking collection_select menu choice to a filter method - Ruby on Rails

so currently within my index I have some collection_select menus which search for the existing values for that field within my database and then list them in a dropdown menu like so

<%= collection_select :ansible_job, :status, AnsibleJob.select(:status).uniq.order('status ASC'), :status, :status, {:prompt => 'Status'},{:name => "status_search"} %>
<%= collection_select :ansible_job, :environment, AnsibleJob.select(:environment).uniq.order('environment ASC'), :environment, :environment, {:prompt => 'Environment'},{:name => "environment_search"} %>
<%= collection_select :ansible_job, :playbook, AnsibleJob.select(:playbook).uniq.order('playbook ASC'), :playbook, :playbook, {:prompt => 'Playbook'},{:name => "playbook_search"} %>

I also have a scope method within my controller for filtering my database based on these values, like so

@ansible_jobs = AnsibleJob.where(nil) # Anon scope
filtering_params(params).each do |key, value|
    @ansible_jobs = @ansible_jobs.public_send(key, value) if value.present?
end

private
def filtering_params(params)
  params.slice(:status, :environment, :playbook)
end

so that I can manually filter my database by posting URL's like

http://localhost:3000/?status=COMPLETED

Now what I would like to do is that when an user chooses a value from the dropdown menu that would call my filter method and link to a search URL with that chosen value appended to the end so that the database is filtered based on that choice. I'm very new to Rails and web development in general so how might be the best way to go about this?

Thanks!

Let me see if I understand you correctly, you want the change on the select to trigger a change in the page, to show a link to a specific URL.

This can be done with javascript listening to the "onChange" event for the select, for example:

function updateURL(sel) {
    var link = document.getElementById("url");
    var value = sel.options[sel.selectedIndex].text;
    var href = "?status=" + sel.options[sel.selectedIndex].text;

    link.innerHTML = "Filter by STATUS: " + value;
    link.href = href;
}

fiddle (this should be improved a lot, but explains the point).

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