how to fill select box with the names of the states corresponding to the country name selected in different select box

hi all ,

can any body guide me, i have to fill the dropdown box with the name of the states of the country at run time which is dependent on the name of the country you selected.

is their any helper exists for this.

thanks sachin

Hi Sachin,

Something like this:

in your controller

@states = State.find_by_country(params[:country])

then in your view

<%= form.collection_select :state_id, @states, :id, :state %>

This example is based on form_for, so if you are using form_tag,
you'll need the additional parameter at the beginning

<%= collection_select :person, :state_id, @states, :id, :state %>

Something like that anyway.

Peace, Phillip

Oy. I just realized that I didn’t read the message closely enough. I see now that you are needing to do one of two things:

  1. post the form when the country is selected, use the code I mentioned earlier (or something similiar) and render the form again, or

  2. use AJAX to query the database and repopulate the state select when the country changes.

I, personally, would go with #2. There is the argument that your app should degrade gracefully if the user doesn’t have JavaScript enabled, but I ignore that since my whole app depends on JavaScript and I doubt that very many people actually have it disabled these days. But that’s an architectural decision that I’ve made. Not everyone would be comfortable with it.

I can provide an example of #2 if you like.

Sorry for the seeming incompetence on my part. I’ll try to read more closely in the future.

Peace,

Phillip

please forward me the example if it is possible for you thanks

one more thing in your code what i realize is that i must have state table in my database, which contains the name of the states for the respective country or it is rails helper kind of thing

please confirm

thanks