Railsアプリケーションにカスケード選択フォームを実装して、市がエリアオプションを更新し、エリアが近隣オプションを更新しようとしています。ただし、以下で実装したソリューションでは、親フィールドの選択に関係なく、3 つのフィールドすべてがすべてのオプションを返します。したがって、たとえば、都市または地域の選択に関係なくすべての近隣が表示され、都市は地域のオプションも更新しません。
私のコードは良さそうで、関連付け (と思います) はすべて適切に設定されています。
都市.rb
has_many :areas
エリア.rb
attr_accessible :name, :city_id
belongs_to :city
has_many :neighborhoods
近所.rb
attr_accessible :name, :area_id
belongs_to :area
私のフォームコード:
<%= form_for @user do |f| %>
<p>City:</p>
<%= f.collection_select(:city_id, @cities, :id, :name, {:prompt => "Select a City"}, {:id => 'cities_select'}) %>
<p>City area:</p>
<%= f.collection_select(:area_id, @areas, :id, :name, {:prompt => "Select an Area"}, {:id => 'areas_select'}) %>
<p>Neighborhood:</p>
<%= f.collection_select(:neighborhood_id, @neighborhoods, :id, :name, {:prompt => "Select a Neighborhood"}, {:id => 'neighborhoods_select'}) %>
コントローラ:
def update_areas
# updates artists and songs based on genre selected
city = City.find(params[:city_id])
# map to name and id for use in our options_for_select
@area = city.areas.map{|a| [a.name, a.id]}.insert(0, "Select an Area")
@neighborhoods = city.neighborhoods.map{|s| [s.title, s.id]}.insert(0, "Select a neighborhood")
end
def update_neighborhoods
# updates songs based on artist selected
area = Area.find(params[:area_id])
@neighborhoods = area.neighborhoods.map{|s| [s.title, s.id]}.insert(0, "Select a neighborhood")
end
update_neighborhoods.js.erb:
$('#neighborhoods_select').html("<%= escape_javascript(options_for_select(@neighborhoods)) %>");
update_areas.js.erb:
$('#areas_select').html("<%= escape_javascript(options_for_select(@areas)) %>");
$('#neighborhoods_select').html("<%= escape_javascript(options_for_select(@neighborhoods)) %>");
コントローラ:
def new
if user_signed_in?
@building = Building.new
@cities = []
@areas = []
@neighborhoods = Neighborhood.all
else
redirect_to new_user_session_path
end
end
フォームが存在する new.html.erb ページの Javascript:
<script>
$(document).ready(function() {
$('#cities_select').change(function() {
$.ajax({
url: "<%= update_areas_path %>",
data: {
city_id : $('#cities_select').val()
},
dataType: "script"
});
});
$('#areas_select').change(function() {
$.ajax({
url: "<%= update_neighborhoods_path %>",
data: {
area_id : $('#areas_select').val()
},
dataType: "script"
});
});
});
</script>
ルート.rb:
get '/users/update_areas', :as => 'update_areas'
get '/users/update_neighborhoods', :as => 'update_neighborhoods'
誰でもこれで私を助けることができますか?
アップデート - -
これで、カスケード collection_select フォームが機能するようになりましたが、フォームを送信すると、次のエラーが発生します。
undefined method `map' for nil:NilClass
Extracted source (around line #29):
<%= f.collection_select(:city_id, @cities, :id, :name, {:prompt => "Select a City"}, {:id => 'cities_select'}) %>
なぜこれが起こったのですか?ビューで @cities の代わりに 'City.all' に変更しようとしましたが、@areas で同じエラーが発生します...