Problem with AJAX Picklists on Edit


I’m using a couple of picklists, populated from database tables, to
take in Country and State in a form. The Countries and States models
are in a belongs_to / has_many relationship, but not all countries
have states available in a picklist (I have them for US and Canada,
but not for the rest of the world). When this happens, I set the
state_id to null and present a textbox for the user to type in the

Anyway, it works fine on initial data entry. However when I use the
same partial to perform an edit on an existing row the information for
the state isn’t being shown correctly (it always shows the first state
in the US list).

Here’s (part of) my _form.rhtml -

========== START OF CUT ==================

<%= @recipient_countries = Country.find(:all, :order => "display_priority,country_name") collection_select(:order, :recipient_country_id, @recipient_countries, :id, :displayname, options = {:prompt => "- Select Country -"}, html_options = { :onChange => "new Ajax.Updater('recipient_states', '/order/recipient_country_changed/' + this[this.selectedIndex].value, {asynchronous:true, evalScripts:true});" } ) %>

<%= render :partial => "recipient_states", :locals => {:recipient_country_id => @recipient_countries[0].id} %> ================ END OF CUT ================

And here is the method “recipient_country_changed” from the controller

=============== START OF CUT ===================
def recipient_country_changed
render :partial => “recipient_states”, :locals =>
{:recipient_country_id => params[:id]}
============== END OF CUT ===================

And finally here is the partial _recipient_states.rhtml -

=============== START OF CUT =====================

<% if State.exists?(["country_id = ?", recipient_country_id]) %> State
<%= collection_select(:order, :recipient_state_id, State.find(:all, :conditions => ["country_id = ?", recipient_country_id]), :id, :state_name, options = {:prompt => "-- Select a State --"} ) %> <% else %> State
<%= text_field 'order', 'recipient_state_text', :size => 20 %> <% end %>

================ END OF CUT =========================

If anyone can suggest a fix for this I’d be very grateful.


Phil Nelson


I got that working … it seems that just coding -

:locals => {:recipient_country_id =>}

in place of

:locals => {:recipient_country_id => @recipient_countries[0].id}

does the trick.

But when I used the same technique further down in my code I started
into an issue, where this was sending through a large negative number
the screen was first displayed (I printed the value), but then when I
the drop boxes thereafter everything was fine. It is as if when I first
display the form that this particular value isn’t getting set up

Any clues ?



This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs