2011-03-29 2 views
3

に選択します。私は選択した都市からの項目のリストを引っ張るしたい都市を選択したときにマルチレベルは、私がこれ持って、私はいくつかのモデル</p> <p>間の複数選択ドロップダウンを使用するレール

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 

をし、次のドロップダウンリストに表示します。ドロップダウンメニュー間の関係を作成するにはどうすればよいですか?誰でも助けてくれますか?

ありがとうございました。

答えて

2

このlinkはあなたに役立つかもしれません。

レール2 +プロトタイプ

APP /モデル/ 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

(、それは重要な答えを持っているので、私は、まだこのフラグを立てるわけではない、注意してくださいしかし...)このリンクは質問に答えるかもしれませんが、答えの本質的な部分をここに含めて参考にしてください。リンクされたページが変更された場合、リンクのみの回答は無効になります。 – JasonMArcher

+1

@ JasonMArcher、そうです、リンクの腐敗が発生する可能性があります。私はしばらくするとすぐに答えを更新します。 – rubyprince

+0

ムチョス・グラ​​シアス(または英語話者からの他の忌々しい結果)。 – JasonMArcher

関連する問題