简体   繁体   English

将collection_select菜单选项链接到过滤器方法-Ruby on Rails

[英]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菜单,这些菜单在数据库中搜索该字段的现有值,然后在下拉菜单中列出它们,如下所示

<%= 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 我的控制器中还有一个scope方法,用于根据这些值过滤数据库,就像这样

@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. 现在,我想做的是,当用户从下拉菜单中选择一个值时,该值将调用我的过滤方法,并链接到搜索URL,并将该选择的值附加到末尾,以便根据该选择对数据库进行过滤。 I'm very new to Rails and web development in general so how might be the best way to go about this? 一般来说,我对Rails和Web开发非常陌生,那么怎么可能是实现此目标的最佳方法?

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. 让我看看我是否理解正确,您是否希望所选内容上的更改触发页面更改,以显示指向特定URL的链接。

This can be done with javascript listening to the "onChange" event for the select, for example: 这可以通过javascript侦听select的“ onChange”事件来完成,例如:

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). 摆弄 (这应该进行很多改进,但是要说明一点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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