I'm trying to display certain stats between two dates (two dropdowns).
My controller has the following method :
def data_stats
data_between_two_dates = Data.where(:created_at => params[:created_at1]..params[:created_at2])
@data_count = data_between_two_dates.count
@gold_data_count = data_between_two_dates.joins(:status).where(status: DataStatus.find(8)).count
puts(@data_count)
puts(@gold_data_count)
I want to be able to display the following variables : data_count
and gold_data_count
in my view, right after selecting two dates from the dropdowns which I populate from my database.
The view is as follows (/views/data_stats/data_stats.html.erb
) :
<select class="my-date" id="created_at1">
<option value="" selected>-- Select Date --</option>
<% datadate = Data.order(created_at: :desc).all %>
<% datadate.each do |data| %>
<%= content_tag(:option, data.created_at, value: data.created_at) %>
<% end %>
</select>
<select class="my-date" id="created_at2">
<option value="" selected>-- Select Date --</option>
<% datadate = Data.order(created_at: :desc).all %>
<% datadate.each do |data| %>
<%= content_tag(:option, data.created_at, value: data.created_at) %>
<% end %>
</select>
<div id="data_stats">
<label class="col-sm-2 control-label">Data count</label>
<span id="data_count"><%= @data_count %></span>
<label class="col-sm-2 control-label">Gold Data count</label>
<span id="gold_data_count"><%= @gold_data_count %></span>
</div>
Within the same view, at the bottom I have the Ajax query :
<script type="text/javascript">
$(document).ready(function() {
$('.my-date').on('change', function() {
var data = {}
$('.my-date').each(function() {
if($(this).val()) {
data[$(this).attr("id")] = $(this).val();
}
});
console.log(data);
// After selecting the two dates
//the above print of `data` gives me this:
//`Object { created_at1: "2016-12-08 16:42:51 UTC", created_at2: "2017-05-23 06:11:02 UTC" }`
if(Object.keys(data).length > 1) {
$.ajax({
type: "GET",
url: "<%= admin_data_stats_path%>",
data: Object.keys(data),
success: function (data) {
console.log("<%= @data_count %>");
console.log("<%= @gold_data_count %>");
//Here when I just print the variables the count is always 0
}
});
}
});
});
</script>
The weird thing is that when I check my terminal after selecting the dates, I can clearly see the result of the puts I made in the controller (I get the count of data and gold data).. But I can't seem to figure out how I can display them in the view.
What am I missing?
Thanks in advance for your help!