0

我有两个模型:国家和用户

国家.rb

class Country < ActiveRecord::Base
  has_many :users
end

用户.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 %>

users/index.html.erb 上还有所有国家的选择菜单。

我该如何执行以下操作:当有人选择特定国家/地区时,只会显示来自所选国家/地区的用户?

4

1 回答 1

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 的方式来做这件事。

于 2012-04-23T06:00:04.823 回答