我试图通过ajax调用来获取rails视图。我收到这个错误:
Started POST "/schools/municipalities" for 127.0.0.1 at 2013-03-07 13:40:11 +0100
Processing by SchoolsController#municipalities as HTML
Parameters: {"Hallands län"=>nil}
School Load (1.9ms) SELECT "schools".* FROM "schools" WHERE "schools"."region" IS NULL
Rendered schools/municipalities.html.erb (0.7ms)
Completed 500 Internal Server Error in 7ms
ActionView::Template::Error (undefined method `map' for nil:NilClass):
1:
2: <%= form_tag 'schools' do %>
3: <p><%= select_tag(:municipalities, options_from_collection_for_select(@municipalities, :municipality, :municipality )) %>
4: </p><p>
5: <%= submit_tag 'Nästa', :class=> 'btn btn-primary' %>
6: </p>
app/views/schools/municipalities.html.erb:3:in `block in _app_views_schools_municipalities_html_erb___826836004410337613_70142825095080'
app/views/schools/municipalities.html.erb:2:in `_app_views_schools_municipalities_html_erb___826836004410337613_70142825095080'
app/controllers/schools_controller.rb:10:in `municipalities'
Rendered /Users/gjores/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.6ms)
Rendered /Users/gjores/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.4ms)
Rendered /Users/gjores/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (12.8ms)
我可以认为我的参数完全没错。我一直试图弄清楚这是怎么回事。
school.js
$(document).ready(function() {
$('#region').change(function(){
region = $(this).val();
$.ajax({
url: "municipalities",
cashe: false,
data: region,
dataType: "HTML",
type: 'POST',
success: function(html){
$("#append").append(html);}
});
});
});
schools.rb controller
class SchoolsController < ApplicationController
def region
@regions = School.select(:region).uniq.order(:region)
end
def municipalities
region = params[:region]
@municipalities = School.where(:region => params[:region]).uniq!{|e| e[:municipality]}
render :layout => false
end
def schools
@user = current_user
@schools = School.where(:municipality => params[:municipalities])
render :layout => false
end
end
地区视图
<%= form_tag 'municipalities' do %>
<p><%= select_tag(:region, options_from_collection_for_select(@regions, 'region', 'region')) %>
</p>
<div id="append">
</div>
<p>
<%= submit_tag 'Nästa', :class=> 'btn btn-primary' %>
</p>
<% end %>
市政当局观点
<%= form_tag 'schools' do %>
<p><%= select_tag(:municipalities, options_from_collection_for_select(@municipalities, :municipality, :municipality )) %>
</p><p>
<%= submit_tag 'Nästa', :class=> 'btn btn-primary' %>
</p>
<% end %>