我試圖在選擇州和城市時顯示圖表。選擇下拉列表中的值後Div未更新
根據第一個下拉列表中的狀態選擇填充城市下拉列表。
問題是當我點擊一個城市沒有圖表顯示,也沒有更新,如果我改變選擇,我似乎無法弄清楚問題。
我正在使用ChartKick以控制器中的查詢給出的值顯示餅圖。
我的代碼如下:
控制器/ city_stats_controller.rb:
def city_stats
@state = params[:state]
@cities = City.where(:state => @state).select(:id, :display_name).uniq.order('display_name ASC')
# @city_id = City.select('id').where(:state => params[:city_state]).where(:name => params[:city_name])
@city_id = City.select('id').find_by_id(params[:city])
dynamic_query = ActiveRecord::Base.send(:sanitize_sql_array, ['SELECT COALESCE(name) as name, count(*) FROM (SELECT name, regs.segment_id, count(*) FROM regs
INNER JOIN segments ON regs.segment_id = segments.id
WHERE regs.city_id = ?
GROUP BY segment_id, name
ORDER BY count(*) DESC) as tabe
GROUP BY name;', @city_id])
@spatial_ratio = ActiveRecord::Base.connection.select_all(dynamic_query)
puts @city_id.inspect #I can see the value printed in the terminal
puts @spatial_ratio.inspect #Same here, even after changing the selection
respond_to do |format|
format.json { render :json => @cities }
format.js {
render json: {
html: render_to_string(
partial: 'city_stats',
locals: {
city_id: @city_id,
spatial_ratio: @spatial_ratio
})
}
}
format.html
end
end
視圖/ city_stats/city_stats.html.erb:
<div class="row">
<label>State <span>:</span></label>
<%= collection_select :city, :state, City.select(:state).uniq.order('state ASC'), :state, :state, {:prompt => 'Select a State'}, {id: 'city_state', multiple: false} %>
<label>City <span>:</span></label>
<%= collection_select :city, :name, [], :name, :name, {:prompt => 'Select a City'}, {id: 'city_name', multiple: false} %>
</div>
<div id="cities">
<!-- Here I render the cities list upon selecting a state-->
<%= render :partial => 'city_stats', :object => @cities %>
</div>
<div id="stats">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#city_state").on('change', function(){
$.ajax({
url: "/admin/city_stats",
type: "GET",
data: {state: $(this).val()},
success: function(data) {
$("#city_name").children().remove();
// Create options and append to the list
var listitems = [];
$.each(data,function(key, value) {
listitems += '<option value="' + value.id + '">' + value.display_name + '</option>';
});
$("#city_name").append(listitems);
//console.log(listitems);
$("#city_name").on('click', function(){
$.ajax({
url: "/admin/city_stats",
type: "GET",
data: {city: $(this).val()},
success: function(data) {
var content = $("#city_name").val()
console.log(content);
$('#stats').replaceWith("<%= j render(partial: 'city_stats') %>");
return content;
}
})
})
}
})
});
});
而在部分:觀點/city_stats/_city_stats.html.erb:
<%= pie_chart @spatial_ratio.rows %>
注意:如果我手動替換控制器中的動態查詢中的city_id,使用隨機id,當刷新頁面時會顯示相應城市的圖表,但我不知道它爲什麼不動態工作
是您在城市工作的點擊事件嗎? 。我的意思是,當你改變城市時,它是否會觸及服務器。 – krishnar
嗨@krishnar再次感謝您的回答!是的,當我更改城市時,我可以在終端中看到新的city_id,以及瀏覽器的控制檯 – GeoSal
,對於遲到的回覆感到抱歉。你能檢查我的解決方案嗎? – krishnar