Based on your example, try this:
In your models (PS: I stripped the lu_ prefix on the class in my example so I explicitly reference the proper table based on your example):
class Country < ActiveRecord::Base has_many :cities def self.table_name() "lu_countries" end end
class City < ActiveRecord::Base belongs_to :country def self.table_name() "lu_cities" end end
In your controller, somewhere appropriate, populate @countries:
@countries = Country.find(:all)
Also, add a new method to your controller to respond to the "observe_field" callback:
def country_changed @cities = Country.find(params[:country_id]).cities render :partial => 'layouts/city_options', :layout => false end
In your view:
<select name="country_id" id="country_id"> <%= render(:partial => 'layouts/country_options', :layout => false) %> <%= observe_field "country_id", :url => {:controller => "YOUR_CONTROLLER", :action => "country_changed"}, :with => "country_id", :update => "city_id" %> </select> <select name="city_id" id="city_id"> </select>
Create two partial views (I have them in the /layouts subdirectory):
_country_options.rhtml <%= options_from_collection_for_select(@countries, :id, :country) %>
_city_options.rhtml <%= options_from_collection_for_select(@cities, :id, :city) %>
The way I have it currently setup, the cities drop down will only be populated when you select a country. But you could set the country to a default for the user, populate the @cities variable as I'm doing in the country_changed method, and then render the city_options partial in the view.
-Paul