我想在多个模型之间使用多个选择下拉列表
我有这个:
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
当我选择一个城市时,我想从所选城市中提取项目列表并在下一个下拉列表中显示。如何在下拉菜单之间创建关系?谁能帮我?
感谢。
答案 0 :(得分:2)
此link可以帮助您完成此操作。
Rails 2 + Prototype
应用程序/模型/ 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>