我正在尝试按照Rails文档和Railscast#88进行操作,但有3个模型。该页面将有3个下拉框用于State,County和&市。我有州>县与JQuery合作。但是当试图为城市建立 grouped_collecion_select 时,事情正在崩溃。
以下是3个型号:
service_area_state.rb
class ServiceAreaState < ActiveRecord::Base
has_many :service_area_counties
default_scope -> { order(name: :asc) }
end
service_area_county.rb
class ServiceAreaCounty < ActiveRecord::Base
belongs_to :service_area_state
default_scope -> { order(name: :asc) }
end
service_area_city.rb
class ServiceAreaCity < ActiveRecord::Base
belongs_to :service_area_county
end
在我的控制器中,我有以下内容:
def index
@states = ServiceAreaState.all
@counties = ServiceAreaCounty.all
@cities = ServiceAreaCity.all
end #index
在视图中我有:
index.html.erb
<div class="row">
<div class="field" id='state_div'>
<%= label_tag :service_area_state_id, "State", id:"service_area_state" %> <br/>
**This works**
<%= collection_select(:service_area_state, :id, @states, :id, :name, prompt: true ) %>
</div>
<div class="field" id='county_div'>
<%= label_tag :service_area_county_id, "County" %><br>
**This works**
<%= grouped_collection_select(:service_area_county, :service_area_county_id, @states, :service_area_counties, :name, :id, :name, prompt: true ) %>
</div>
<div class="field" id='city_div'>
<%= label_tag :service_area_city_id, "City" %><br>
**This does not work**
<%= grouped_collection_select(:service_area_city, :service_area_county_id, @counties, :service_area_cities, :name, :id, :name, prompt: true ) %>
</div>
</div>
我收到以下错误:
undefined method `service_area_cities' for #<ServiceAreaCounty:0x007fb5e7dac060>
在这一行:
<%= grouped_collection_select(:service_area_city, :service_area_county_id, @counties, :service_area_cities, :name, :id, :name, prompt: true ) %>
有人可以找到我出错的地方吗?
谢谢!
答案 0 :(得分:1)
您需要将service_area_cities设置为ServiceAreaCounty模型中的关联(听起来像是一个has_many关联):
class ServiceAreaCounty < ActiveRecord::Base
belongs_to :service_area_state
has_many :service_area_cities
default_scope -> { order(name: :asc) }
end