2012-04-23 92 views
0

更改内容我有两个型号:国家和用户与选择菜单

country.rb

class Country < ActiveRecord::Base 
    has_many :users 
end 

user.rb

class User < ActiveRecord::Base 
    belongs_to :country 
end 

所有用户(来自所有国家)显示在users/index.html.erb页面上。

users_controller.rb

def index 
    @users = User.all 
    end 

用户/ index.html.erb

<%= collection_select(:user, :country_id, Country.all, :id, :country_name) %> 
<%= render @users %> 

还有与用户/ index.html.erb所有国家都选择菜单。

我该如何做到以下几点:当某人选择特定的国家时,将只显示来自选定国家的用户?

回答

1

这只能使用javascript来实现。

这样做的典型方法是使用AJAX。将onchange事件绑定到请求选定国家/地区的所有用户列表的选择。在服务器上,您可以将该查询格式化为一组选择选项,然后插入,然后将响应插入客户端的第二个下拉列表中。

这看起来像一个很好的教程: http://www.falsepositives.com/index.php/2010/05/28/building-a-casscading-drop-down-selection-list-for-ruby-on-rails-with-jquery-ajax/

虽然你应该试着去找到这样做的更加RESTful方式。