---
title: "rubyonrails 下实现菜单级联"
author: "PBFox"
date: "2008-06-19T22:13:00Z"
tags: []
slug: "rubyonrails"
draft: false
lastmod: "2008-06-19T22:13:00Z"
id: 479232
url: "https://developerwork.iteye.com/blog/479232"
---

很多时候我们需要实现菜单的级联。那么在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 &lt; ActiveRecord::Base belongs\_to :country has\_many :people end class Country &lt; ActiveRecord::Base has\_many :cities has\_many :people end class Person &lt; ActiveRecord::Base belongs\_to :country belongs\_to :city end 第四，修改app/views/layouts/people.rhtml，包含prototype： &lt;%= javascript\_include\_tag 'prototype' %&gt; 第五，修改people/new.html.erb &lt;p&gt; &lt;b&gt;Country&lt;/b&gt;&lt;br /&gt; &lt;%= f.select (:country\_id, Country.find(:all).collect {|c| \[ c.name, c.id ] }, { :include\_blank =&gt; true }, :onchange =&gt; remote\_function(:update =&gt; "cities", :method =&gt; "get", :with =&gt; "'country\_id=' + value + '&partial=select'", :url =&gt; { :controller =&gt; :cities, :action =&gt; :index})) %&gt; &lt;/p&gt;&lt;p&gt; &lt;b&gt;City&lt;/b&gt;&lt;br /&gt; &lt;div id="cities"&gt; &lt;%= f.select (:city\_id, \[]) %&gt; &lt;/div&gt; &lt;/p&gt; 第六，修改city\_controller 的index方法: def index if params\[:country\_id] @cities = City.find(:all, :conditions =&gt; \["country\_id = ?", params\[:country\_id]]) else @cities = City.find(:all) end respond\_to do |format| format.html { render :partial =&gt; params\[:partial]} format.xml { render :xml =&gt; @districts.to\_xml } end end 第七：创建\_select.html.erb模板 &lt;%= select(:person, :city\_id, @cities.collect {|c| \[c.name, c.id]}) %&gt;