rubyonrails 下實現菜單級聯

很多時候我們需要實現菜單的級聯。那麼在ROR中怎麼實現: 首先 分別創建3個資源: ruby script/generate scaffold country name:string ruby script/generate scaffold city country_id:integer name:string ruby script/generate scaffold person country_id:integer city_id:integer name:string 他會分別創建國家、城市、人員3個資源 其次,創建數據庫。 rake db:create創建數據庫 rake db:migrate 遷移數據 第三,model建立關係 class City < ActiveRecord::Base belongs_to :country has_many :people end class Country < ActiveRecord::Base has_many :cities has_many :people end class Person < ActiveRecord::Base belongs_to :country belongs_to :city end 第四,修改app/views/layouts/people.rhtml,包含prototype: <%= javascript_include_tag 'prototype' %> 第五,修改people/new.html.erb

Country
<%= f.select (:country_id, Country.find(:all).collect {|c| [ c.name, c.id ] }, { :include_blank => true }, :onchange => remote_function(:update => "cities", :method => "get", :with => "'country_id=' + value + '&partial=select'", :url => { :controller => :cities, :action => :index})) %>

City

<%= f.select (:city_id, []) %>

第六,修改city_controller 的index方法: def index if params[:country_id] @cities = City.find(:all, :conditions => ["country_id = ?", params[:country_id]]) else @cities = City.find(:all) end respond_to do |format| format.html { render :partial => params[:partial]} format.xml { render :xml => @districts.to_xml } end end 第七:創建_select.html.erb模板 <%= select(:person, :city_id, @cities.collect {|c| [c.name, c.id]}) %>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章