Folks,
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
state.
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 ==================
Country
<%=
@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});"
}
)
%>
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
============== 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
%>
If anyone can suggest a fix for this I’d be very grateful.
Thanks
Phil Nelson