2016-04-28 129 views
0

我試圖按照Rails Docs和Railscast#88,但有3個模型。該頁面將有3個下拉框供州,縣,&城市使用。我有State> County使用JQuery。但是當試圖爲城市建造grouped_collecion_select事情正在破裂。Rails grouped_collection_select與3個模型

這裏有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) %> 

有人點我哪裏錯了?

謝謝!

回答

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 
+0

這個固定我的問題,不能相信我忽略這麼簡單的東西。 – David