Re: Tutorial on field_observer?

Taylor Strait
Fri, 29 Dec 2006 17:55:58 -0000

Paul,

Thanks!  I found that thread late last night and worked into the wee
hours of the morning getting it working.  It was pivotal to my success.
The only difference in my usage was I had to use page.replace_html
because I had two levels of dependency and render :partial can only
update one item.  Thanks again for that tutorial!  Here is how I did it
for the archives:

---------VIEWS-----------
******_form:*********

  <%= render(:partial => ''country_options'', :layout
=> false) %>

  <%= render(:partial => ''state_options'', :layout =>
false) %>

  <%= render(:partial => ''city_options'', :layout =>
false) %>

********_country_options:*********

Country
    <select name="building[country]"
id="building[country]">
--
        <%= options_from_collection_for_select(@countries, :id, :name)
%>
        <%= observe_field "building[country]",
             :url     => {:controller => "buildings", :action
=>
"country_changed"},
             :with    => "building[country]",
             :update  => "building[state]" %>



*****_state_options:*******


State / Region
    <select name="building[state]"
id="building[state]">
--
    <%= options_from_collection_for_select(@states, :id, :name) %>
          <%= observe_field "building[state]",
               :url     => {:controller => "buildings", :action
=>
"state_changed"},
               :with    => "building[state]",
               :update  => "building[city]" %>




*******_city_options:******


City

--
    <%= options_from_collection_for_select(@cities, :id, :name) %>




-----CONTROLLER--------
  def create
    if session[:person_id]
      unless params[:building]
        @building = Building.new
        @countries = Country.find(:all)
        @states = []
        @cities = []
      else
        @building = Building.new(params[:building])
        @building.save
        flash[:notice] = ''Building was successfully created.''
        redirect_to :action => ''list''
      end
    else
      redirect_to :controller => ''login'', :action =>
''login''
    end
  end

  def country_changed
    # avoid freaking out if user deselects country
    if params[:building][:country] == "0"
      @states = []
    else
      @states = Country.find(params[:building][:country]).states
    end
    @cities = []

    # update state list and reset city list
    render :update do |page|
      page.replace_html ''state_options'', :partial =>
''state_options''
      page.replace_html ''city_options'', :partial =>
''city_options''
    end
  end

  def state_changed
    # avoid freaking out if user deselects state
    if params[:building][:state] == "0"
      @cities = []
    else
      @cities = State.find(params[:building][:state]).cities
    end

    # update city list
    render :update do |page|
      page.replace_html ''city_options'', :partial =>
''city_options''
    end
  end

--
Posted via http://www.ruby-forum.com/.