多くのビュー(new.html.erbおよびedit.html)に存在するこのAJAXコード(http://badpopcorn.com/blog/2008/09/11/rails-observer-field/から取得)があります.erb ほとんど)。コードの重複を避けるために、パーシャルを使用するふりをします。
アプリ/ビュー/都市/_state_city_form.html.erb
<p> State:
<%= select(:state, :state_name, City.all(:select => 'DISTINCT(state)', :order => :state).collect {|c| [ c.state.titleize, c.state ] }, {:include_blank => true})%>
<%= observe_field 'state_state_name', :url => { :action => :by_state,
:controller => :cities },
:update => 'cities_list',
:with => "'state='+ $('#state_state_name').val()" %>
</p> City:
<div id="cities_list">
<%= select(modelname.to_sym, :city_id, [], {:include_blank => true})%>
</div>
<p>
</p>
また、Ajax コールバック コンテンツもあります。
アプリ/ビュー/都市/by_state.html.erb
<%= select(/*PROBLEM_HERE*/, :city_id, @cities.collect {|c| [ c.name, c.id ] }, {:include_blank => true})%>
そして私の都市コントローラー:
app/controllers/cities_controller.rb
class CitiesController < ApplicationController
def by_state
@cities = City.find_all_by_state(params[:state])
render :layout => false
end
end
次に、必要な場所からすべてのパーシャルを呼び出すだけです。
アプリ/ビュー/ユーザー/new.html.erb
...
<%= render :partial => 'cities/state_city_form', :locals => { :modelname => :user } %>
...
アプリ/ビュー/従業員/new.html.erb
...
<%= render :partial => 'cities/state_city_form', :locals => { :modelname => :employee } %>
...
ここで : userまたは:employeeをパーシャルに渡すことができますが、それらを Ajax コールバックに渡すにはどうすればよいでしょうか?