尝试从同一个表中的选定状态填充美国县的数据库。尝试使用此方法here is the link
在Rails 5中实现到目前为止,我能够在浏览器控制台中找出并看到正在进行的呼叫以及正确的数据返回,但是下拉永远不会得到更新。我试图弄乱不同的路线,但仍然没有运气。请,任何帮助将不胜感激。
#routes
get 'account/main/_update_weather', :to => 'client/main#_update_weather', :as
=> :client_location_java
get 'account/_location', :to => 'client/main#_location', :as =>
:client_location
#controller ../controllers/client/main_controller.rb
def _location
@weathers = Weather.all
@profile = Profile.new
@county_name = Weather.where("state_code = ?", "AL")
end
def _update_weather
@county_name = Weather.where("state_code = ?", params[:state_code])
respond_to do |format|
format.js
end
end
#Ajax /assets/javascripts/location.js.coffee
$ ->
$(document).on 'change', '#state_select', (evt) ->
$.ajax 'main/_update_weather',
type: 'GET'
dataType: 'html'
data: {
state_code: $("#state_select option:selected").val()
}
success: (data, textStatus, jqXHR) ->
console.log("Dynamic county select OK!")
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
#View for update ../client/main/_update_weather.html.erb
<script>
$("#county_select").empty()
.append("<%=j render(:partial => @county_name) %>")
</script>
<% @county_name.each do |a| %>
<option value="<%= a.id %>"><%= a.county_name %></option>
<% end %>
#view which trying to update ../client/main/_location.html.erb
<% content_for :head do %>
<%= javascript_include_tag 'location', :media => "all", 'data-turbolinks-
track' => true %>
<% end %>
<%= select_tag "state", options_for_select(state_code) {},
{ id: 'state_select' } %>
<%= f.select :weathers_id, options_for_select(@county_name.collect {|a|
[a.county_name, a.id] }, 0), {}, { id: 'county_select' } %>
#Console输出
Started GET "/account/main/_update_weather?state_code=CA" for 127.0.0.1 at 2017-07-17 22:49:11 -0700
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 10 ORDER BY `users`.`id` ASC LIMIT 1
Processing by Client::MainController#_update_weather as HTML
Parameters: {"state_code"=>"CA"}
Rendering client/main/_update_weather.html.erb
Weather Load (3.4ms) SELECT `weathers`.* FROM `weathers` WHERE (state_code = 'CA')
Rendered collection of client/weathers/_weather.js.erb [56 times] (0.7ms)
Rendered client/main/_update_weather.html.erb (8.0ms)
Completed 200 OK in 17ms (Views: 12.0ms | ActiveRecord: 3.4ms)