Problems with observe_field JAX call

I have created a view that uses observer_field to send an ajax request
when the value in the country select box changes. View code is as below:

 Country: <%=

options = [[“Select Country”, " "]] +
@my_countries.collect {|c|[ c.name, c.id]}
select( “country”, “id”, options, {:selected => 0}) %>

 <%= observe_field(:country_id,
             :update => "city_list",
             :url => { :action => :find_cities_by_country },
             :with => "'country_id='+value") %>


   <%= render :partial => "city", :collection => @cities %>

Controller code that finds all the cities for a country is as below:

def find_cities_by_country

@cities = City.find_all_by_country_id(params[:country_id])
render(:partial => “city”, :collection => @cities, :layout => false)

end

partial template _city.rhtml is as below:

<% if city %> <%= city.name %>
<% end %>

Now let’s say I selected United States in select list. I see cities New
York and Fremont (I have only two cities in US for now) in the browser.
So far so good.

Now If I select another country say Canada which has one city for now
(say Toronto). I see New York and Toronto in the browser but I expected
to see only Toronto. Do I need to somehow clear all the contents of div
before second AJAX call is made. If so how do I do that?

–Jeet

I am not too sure but I think the problem is that the


element is included in the partial template too. So first you add USA
and
then you choose Canada it would come inside the div with id=“city_list”
.whcih already has US cities .It will not overwrite the US cities.
You must not include this div tag in the partial .The partial should
return
exactly whats supposed to be inside the :update element (by default) if
you
dont mention any :position
Let me know if thats the problem
vivek

Now let’s say I selected United States in select list. I see cities New

Well I was able to find another solution which works well for me.

In my controller the call to render was changed to:

render(:partial => “city”, :object => @cities)

NOTE: now using :object instead of :collection

and changed partial _city.rhtml to:

<% if @cities %>

City: <%= options = [[" Select City", " "]]+ @cities.collect {|c|[ c.name, c.id]} select( "city", "id", options) %>

<% end %>

–Jeet

krishna.vivek wrote:

I am not too sure but I think the problem is that the


element is included in the partial template too. So first you add USA
and
then you choose Canada it would come inside the div with id=“city_list”
.whcih already has US cities .It will not overwrite the US cities.
You must not include this div tag in the partial .The partial should
return
exactly whats supposed to be inside the :update element (by default) if
you
dont mention any :position
Let me know if thats the problem
vivek

Now let’s say I selected United States in select list. I see cities New