rails,从下拉菜单中选择不会触发不同的过滤器

时间:2014-11-18 11:56:32

标签: javascript ruby-on-rails ruby

我有一个事件表,我想根据下拉菜单中的选项进行过滤。但是当我选择一个不同的项目时没有触发任何动作,我只是默认打开。视图似乎正在工作,我显示的表和包含项目的框,只是选择不会改变任何东西。我猜测我的选择不会触发事件,因此.coffee中的部分是错误的。在这里相关的代码,我希望有人可以提供帮助:

events.rb

scope :men, -> { where(team_id: 1) }
scope :women, -> { where(team_id: 2) }
scope :juniors, -> { where(team_id: 3) }

events_controller.rb

def index
    @events = Event.where("startdate >= ?", Date.today)
               .order("startdate, starttime")

    @events = apply_type_filter(@events)
end

def apply_type_filter(relation)
   case params[:filter]
   when "Men" 
      relation.men
   when "Women" 
      relation.women 
   when "Juniors"
      relation.juniors
   else
      relation
   end
end

index.html.erb

<div class="left">
<%= form_tag events_path, :method => 'get' do %>  
    <%= select_tag "filter", options_for_select([ "Alle", "Men", "Women", "Juniors" ], params[:filter]), class: 'my_filter' %>
<% end %>

events.js:

$(function(){
 $('select.my_filter').on('change', function(){
  alert($(this).val())
  $(this).closest('form').submit()
 })
})

运行页面时生成以下html代码:

<div class="left">
<input type="text" class="filter" id="events-filter-input" placeholder="Termine filtern" />
<form accept-charset="UTF-8" action="/events" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div>  
    <select class="my_filter" id="filter" name="filter"><option value="Alle">Alle</option>
<option value="Men">Men</option>
<option value="Women">Women</option>
<option value="Juniors">Juniors</option></select>
</form></div>

如果它也有助于jacasvript代码:

的application.js:

// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from example.com/assets/…
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require jquery.ui.core
//= require jquery.ui.datepicker.js
//= require_tree .

application.html.erb:

<%= javascript_include_tag "application" %>

感谢您的帮助。作为补充,我想让用户可以定义应该首先为他显示哪个选择。我该怎么办?

谢谢

1 个答案:

答案 0 :(得分:1)

DOM加载可能存在问题。您可以尝试以下两种方法之一: 1)复制event.js中的JS并将其放在Index页面底部的标签中。 2)全部删除event.js,然后将:onchange => "this.form.submit()添加到select_tag。 这些是粗略的,现成的方法,在类似的情况下对我有用。