My problem involves passing values from JS to controller and then using them to query and return some output data. These values are as a result of selections in the UI:
<!-- Select car make -->
<ul id = "make">
<% Car.all.each do |c| %>
<li><%= link_to c.make, todos_data_path(:make_id => c.id), :method => :post, remote: true %></li>
<% end %></ul>
<!-- Select car body -->
<ul id = "body">
<% Type.all.each do |t| %>
<li><%= link_to t.name, todos_data_path(:body_id => t.id), :method => :post, remote: true %></li>
<% end %></ul>
Extract the selected values in JS:
var make = $('#make').text();
var body = $('#body').text();
After searching I learnt from a post that one cannot pass variables from JS to Rails directly. Instead, pass values to the controller by appending them as params in url. From my understanding what I need can be done in three basic steps:
Step 1: Create query string parameters using JavaScript. One way way to do this:
var url = "http://www.myapp/todos/data?" + $.param({make_id: make, body_id: body})
//http://www.myapp/todos/data?make_id=4&body_id=3
Step 2: Append the query string to the url. Following an earlier question one can append the query string to url by:
window.open(url, "_self");
Step 3: Run the url string and use params in the controller.
My routes:
resources : todos, only: [:index, :new, :create , :destroy]
get '/todos/data (:make_id)(:body_id)' => 'todos#data'
Controller:
def data
@make = params[:make_id]
@body = params[:body_id]
@vehicles = Vehicle.where(make: @make, body: @body )
respond_to do |format|
format.html{ redirect_to root_path }
format.js { }
end
end
The output after running the string in the url:
Started GET "/todos/data?make_id=2&body_id=3" for 10.240.0.185 at 2017-05-24 12:55:58 +0000
Processing by TodosController#data as HTML
Parameters: {"make_id"=>"2", "body_id"=>"3"}
Redirected to http://myapp/
Completed 302 Found in 4ms (ActiveRecord: 0.6ms)
It seems that everything works fine up to the point where there is redirect_to root_path. I would like instead format.js { } executed since my aim is to render data.js.erb. How can I make the action respond to JS format instead of HTML? I tried specifying in the route get '/todos/data(:make_id)(:body_id)' => 'todos#data', :defaults => { :format => 'js { }' } but it generated unknown format error .
I have posted the whole process of what I am trying to do for clarity on what I want to achieve and maybe get suggestions on how to do the whole thing differently.
EDIT: I need also to show my todo.js
$( document ).on('turbolinks:load', function() {
$('#make').on('click', 'li', function (event){
event.preventDefault();
$('.active').removeClass('active');
var text = $(this).text();
$(this).addClass('active');
});
$('#body').on('click', 'li', function (event){
event.preventDefault();
$('.active').removeClass('active');
var text = $(this).text();
$(this).addClass('active');
});
});