开发者

Multilevel select on rails

I want to use multiple select drop-down between several models

I have this:

class Report < ActiveRecord::Base
  belongs_to :region
end

class City < ActiveRecord::Base
  has_many :regions
end

class Region < ActiveRecord::Base
  has_many :reports
  belongs_to :city
end
开发者_JAVA百科

when I select a city I want to pull list of items from selected city and show it on next drop-down list. How do I create relationships between drop-down menus ? Can anyone help me?

Thanks.


This link may help you in doing it.

Rails 2 + Prototype

app/models/cities.rb

class City < ActiveRecord::Base
  has_many :regions
  has_many :reports, :through => :regions # this is newly added
end

cities_controller

class CitiesController < ApplicationController
  def index
    @cities  = City.find(:all)
    @regions = Region.find(:all)
    @reports   = Report.find(:all)
  end

  def update_regions
    # updates regions and reports based on city selected
    city = City.find(params[:city_id])
    regions = city.regions
    reports   = city.reports

    render :update do |page|
      page.replace_html 'regions', :partial => 'regions', :object => regions
      page.replace_html 'reports',   :partial => 'reports',   :object => reports
    end
  end

  def update_reports
    # updates reports based on region selected
    region = Region.find(params[:region_id])
    reports  = region.reports

    render :update do |page|
      page.replace_html 'reports', :partial => 'reports', :object => reports
    end
  end
end

_reports.html.erb

<%= collection_select(nil, :report_id, reports, :id, :title,
                     {:prompt   => "Select a Report"}) %>

_regions.html.erb

<%= collection_select(nil, :region_id, regions, :id, :name,
                     {:prompt   => "Select a Region"},
                     {:onchange => "#{remote_function(:url  => {:action => "update_reports"},
                                                      :with => "'region_id='+value")}"}) %>
<br/>

index.html.erb

<%= javascript_include_tag :defaults %>
<%= collection_select(nil, :city_id,  @cities,  :id, :name,
                      {:prompt   => "Select a City"},
                      {:onchange => "#{remote_function(:url  => {:action => "update_regions"},
                                                       :with => "'city_id='+value")}"}) %>
<br/>
<div id="regions"><%= render :partial => 'regions', :object => @regions %></div>
<div id="reports"><%= render :partial => 'reports',   :object => @reports %></div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜