使用rails中的数据库填充动态选择菜单

时间:2013-03-05 19:06:37

标签: ruby-on-rails-3 activerecord

我尝试根据上一菜单中的用户选择填充选择菜单。我只使用一种模型,其中存储了用户正在过滤的所有记录。我遇到的问题是只获得唯一记录,而不是基于之前选择的所有记录。

schools_controller

    class SchoolsController < ApplicationController
  def region
    @user = current_user
    @regions = School.select(:region).uniq.order(:region)
  end

  def municipalities
    @municipalities = School.where(:region => params[:region]).uniq



  end
end 

模型

    # == Schema Information
#
# Table name: schools
#
#  id           :integer          not null, primary key
#  region       :string(255)
#  municipality :string(255)
#  school       :string(255)
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#

class School < ActiveRecord::Base
  attr_accessible :region, :municipality, :school
  has_many :users
end

regions.html.erb

 <%= form_tag 'municipalities' do %>
<p><%= select_tag(:region, options_from_collection_for_select(@regions, 'region', 'region')) %>
</p><p>
<%= submit_tag 'Nästa', :class=> 'btn btn-primary' %>
    </p>
<% end %>

municipalities.html.erb

<%= form_tag 'schools' do %>
<p><%= select_tag(:municipalities, options_from_collection_for_select(@municipalities ,:municipality ,:municipality )) %>
</p><p>
<%= submit_tag 'Nästa', :class=> 'btn btn-primary' %>
    </p>
<% end %>

1 个答案:

答案 0 :(得分:0)

在动态选择菜单http://railscasts.com/episodes/88-dynamic-select-menus-revised上查看Ryan的railscast。或者看一下dynamic_form gem。

两者都有诀窍,dyanic_form gem会像你期望的那样采用大量的编码,并使用更多的coffescript而不是javascript