views:

61

answers:

1

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?

A: 

You can try to pass the model name as string to the partial and convert it to symbol using to_sym.

Hope this helps.

Hitesh Manchanda
I thought so, but how pass the model name to the ajax callback ? app/views/cities/by_state.html.erb
benoror
@benoror can u please put the code for you ajax call also as i am not able to understand where do u want to call it exactly.
Hitesh Manchanda
Done, hope it's more clear, look at /*PROBLEM HERE*/.
benoror
Finally figured out, passing model name into ":with" hash
benoror