I have this piece of AJAX code (took from: http://badpopcorn.com/blog/2008/09/11/rails-observer-field/) that is present in many views (new.html.erb and edit.html.erb mostly). To avoid code duplication I pretend to make use of partials:
app/views/cities/_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>
Also I have the Ajax callback content:
app/views/cities/by_state.html.erb
<%= select(/*PROBLEM_HERE*/, :city_id, @cities.collect {|c| [ c.name, c.id ] }, {:include_blank => true})%>
And my cities controller:
app/controllers/cities_controller.rb
class CitiesController < ApplicationController
def by_state
@cities = City.find_all_by_state(params[:state])
render :layout => false
end
end
Then I would simply call the partial in every from where's is needed:
app/views/user/new.html.erb
...
<%= render :partial => 'cities/state_city_form', :locals => { :modelname => :user } %>
...
app/views/employee/new.html.erb
...
<%= render :partial => 'cities/state_city_form', :locals => { :modelname => :employee } %>
...
Here I can pass :user or :employee to the partial, but how can I pass them to the Ajax callback?