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]}) %>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章