rails中联级菜单的一种实现方式

Posted by HoLin on December 30th, 2007 filed in Rails应用

通过Ajax实现联级菜单。

典型应用场景:两个下拉框(select),第一是省份的选择,第二个是城市的选择。在省份选择定之后,第二个select显示选中省份对应的城市。也就是说城市要根据所选的省份过滤。

实现方式:在切换省份的同时,向server端请求对应省份下的city,生成select HTML代码替换原city select,

具体如下。view中:

1
2
3
4
<label><label>省份:</label>
<%= select :profile, :province_id, Province.for_select, {},  :onchange => remote_function(:with => "'province_id=' + value", :url => {:action => 'get_city_select', :controller => 'cities'}, :update => 'city_select') %>
<label>城市:</label><span ID="city_select"><%= select :profile, :city_id, City.for_select %></span>
</label>

controller中:

1
2
3
4
def get_city_select
@cities = City.find_all_by_province_id(params[:province_id])
render :partial => 'cities_select', :object => @cities
end

partial _cities_select中:

<%= select_tag 'profile[city_id]', options_for_select(cities_select.collect { |p| [p.name, p.id] })%>

Related posts:

  1. 使用Ultrasphinx实现多Model搜索 Sphinx是由俄罗斯(让人想起了Nginx:)人Andrew开发的全文搜索引擎。Ultrasphinx则是一个使用该引擎的Rails插件。本文介绍如何使用Ultrasphinx使用多Model搜索。 系统环境: Leopard 10.5.2 MySql 5.0.45 Rails 2.0.2 注:Linux与之类似。Win平台需选择安装Sphinx的windows版本。 安装...

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Comment