簡體   English   中英

在JavaScript的幫助下使用參數重定向Collection_select

[英]Collection_select redirecting with parameters with the help of javascript

當我從下拉菜單中進行更改時,我試圖將用戶重定向到路由“出勤/:域”。 我正在使用javascript執行此操作。 較早的實現如: window.location = "<%= url_for(:controller => 'attendance', :action => 'index') %>?" + id; 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:

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

在此實現中,我重定向到的鏈接是: http://localhost:3000/attendance/ + trainerId +這不是我想要的。 而不是trainerId,它應該是該變量的值。 有什么建議嗎?
最后,我的問題是:如何使用collection_select重定向參數。 該下拉菜單將在同一頁面上可用,因此需要相應地更改參數,與上述情況不同。

從根本上講,您無法執行此操作-您無法調用ruby函數,該函數在頁面顯示時僅使用javascript知道的參數在服務器端進行評估(除非您發出Ajax請求)。

js-routes gem使用您的路由文件來創建所有已命名路由的javascript實現:

Routes.attendance_domain_path(id)

在您的JavaScript中。 如果僅是一條路線,那可能會有點過大。

只需將完整的url通過proccollection_select傳遞給redirectToIndex() 嘗試以下操作:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM