Basically, I have multiple-select box in the page. When the select box is changed, i want to put in session all id's being selected (one or more). The reason why i need something like that is following:
While creating new product user can create many variants of that product based on selected options(for example: Color and Size)(id's mentioned above). So for example one product can have 2 variants(T-shirt in black color with size XL and green T-shirt with size L)
First of all i created POST route in products controller on which through AJAX i will send selected options:
resources :products do
collection do
post 'ajaxify_options'
end
end
Ajax code
$('#variant-options').change(function() {
var option_values = [];
$("#variant-options option:selected").each(function() {
option_values.push($(this).val());
});
$.ajax({
url: '/products/ajaxify_options',
type: 'POST',
data: ({'ids': option_values})
});
});
ajaxify_options action
def ajaxify_options (inside product controller)
set_option_values params[:ids]
head :ok, :content_type => 'text/html'
end
Here set_option_values
is method in ApplicationController
defined as:
def set_option_values option_values
session[:option_values] = [] if session[:option_values].nil?
session[:option_values] = option_values
end
with get
method also (implemented as helper_method
inside ApplicationController
)
def get_option_values
return [] if session[:option_values].nil?
session[:option_values]
end
So now when user choose option (one or more) through get_option_values
i can access to selected options from anywhere i need (partials for creating new product and variants).
Main-problem: When user select one or more options, through debugging i see that there is NO errors with ajax or server-side code everything is just fine and i can inspect values of selected options. But rails DO NOT reload session data immediately after AJAX call BUT only when i reload whole page.
Side-problem: Is everything fine with this code, i don't know why i think that I violate some Rails practices with populating session through ajax?
Similar question that i find is: Rails not reloading session on ajax post
I tried that solution but result is same.