Rails grouped_collection_select 有 3 个模型

Rails grouped_collection_select with 3 models

我正在尝试遵循 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 )   %>

谁能指出我哪里出错了?

谢谢!

您需要在 ServiceAreaCounty 模型中将 service_area_cities 设置为关联(听起来像是 has_many 关联):

class ServiceAreaCounty < ActiveRecord::Base
  belongs_to :service_area_state
  has_many :service_area_cities
  default_scope -> { order(name: :asc) }
end