Lucian Tarna
Lucian Tarna

Reputation: 1827

Collection_select redirecting with parameters with the help of javascript

I am trying to make a redirect the user to a route 'attendance/:domain' when the option from the dropdown that I made changes. I am doing this using javascript. Earlier implementations like: window.location = "<%= url_for(:controller => 'attendance', :action => 'index') %>?" + id; just add the id to the earlier link so if I had 'attendance/2' it would become 'attendance/23' instead of 'attendance/3' . So I am trying to use the path provided by ruby like so:

config.rb:

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

view:

<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 + ")) %>";
  } 

In this implementation the link that I am redirected to is : http://localhost:3000/attendance/ + trainerId + which is not what I wanted. Instead of trainerId it should be the value of that variable. Any tips please ?
In the end my question is : How can I redirect with parameters using collection_select. This dropdown will be available on the same page so the parameters need to change accordingly not like in the situation described above.

Upvotes: 1

Views: 374

Answers (2)

Oleg K.
Oleg K.

Reputation: 1549

Just pass the full url to redirectToIndex() from collection_select via proc. Try this in view:

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

In JS:

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

}

Upvotes: 1

Frederick Cheung
Frederick Cheung

Reputation: 84132

You fundamentally can't do this - you can't call a ruby function, evaluated serverside with a parameter known only to your javascript at page display time (unless of course you make an Ajax request).

The js-routes gem uses your routes file to create javascript implementations of all the named routes: you'd be able to do

Routes.attendance_domain_path(id)

In your javascript. If it's just the one route then that might be a bit overkill.

Upvotes: 1

Related Questions