Collection_select借助javascript重定向参数

时间:2015-04-18 09:18:07

标签: javascript ruby-on-rails ruby

我正在尝试将用户重定向到路线&#39; attendance /:domain&#39;当我做的下拉列表中的选项发生变化时。我是用javascript做的。早期的实施方式如:window.location = "<%= url_for(:controller => 'attendance', :action => 'index') %>?" + id;只是将ID添加到之前的链接中,因此如果我有'attendance/2',它将变为'attendance/23'而不是'attendance/3'。所以我试图使用ruby提供的路径,如下所示:

config.rb:

get 'attendance/:domain', to: 'attendance#index', as: 'attendance_domain'

观点:

<div class="form-group col-lg-3 col-md-5 ">
        <%= label_tag(:domain, "Domeniu", class: "control-label") %>
        <%= collection_select(nil, :id, @domains, :id, :complete_name, {selected: -1}, {:onchange=> "redirectToIndex(this.value)",:selected => params[:domain],class: "form-control"}) %>
    </div>

javascript in view:

function redirectToIndex(trainerId){
     window.location ="<%= url_for(attendance_domain_path(" + trainerId + ")) %>";
  } 

在此实现中,我被重定向到的链接是:http://localhost:3000/attendance/ + trainerId +这不是我想要的。而不是trainerId它应该是该变量的值。有什么提示吗?
最后我的问题是:如何使用collection_select重定向参数。此下拉列表将在同一页面上提供,因此参数需要相应更改,而不是像上述情况那样。

2 个答案:

答案 0 :(得分:1)

您根本无法做到这一点 - 您无法调用ruby函数,在页面显示时使用只有javascript知道的参数来评估服务器端(当然,除非您发出Ajax请求)。< / p>

js-routes gem使用您的路由文件来创建所有命名路由的javascript实现:您能够做到

Routes.attendance_domain_path(id)

在你的javascript中。如果它只是一条路线那么可能有点矫枉过正。

答案 1 :(得分:1)

只需将完整的网址从redirectToIndex()通过collection_select传递给proc。在视图中尝试这个:

<%= collection_select(nil, :id, @domains, -> (d) {attendance_domain_path d},
  :complete_name, {selected: -1}, {:onchange=> "redirectToIndex(this.value)",
  :selected => params[:domain],class: "form-control"}) %>

在JS中:

function redirectToIndex(val){
 window.location = val;

}