Search code examples
ruby-on-railsrubyruby-on-rails-2

How can i update my lisbox using ajax?


How can i create an ajax in my search when i select a country it would show me all states that i have in the country selected

I'm trying to create a display when i select country automatically show all the states that has the country selected

My tables

Countries

  |id| |country_name|
   1    'USA'
   2     'Peru'

States

   |id| |state_name|
    1      Alabama
    2      Machupicchu

Country_States
    |id|  |country_id|   |state_id|
     1       1              1
     2       2              2

My controller

 class Country_StatesController < ApplicationController
  def conditional

    @countries = Country.find(:all)
    @states= State.find(:all)

    @selected_country = Country.find_by_id(params[:countries])  if params[:countries].to_i
    @selected_state = State.find_by_id(params[:states])  if params[:states].to_i
    @search= CountryState.find(:all,:conditions=> ['state_id','country_id' ],params[:states],params[:countries] )
  end
 end

My view

<% form_tag :controller=>"country_States",:action=>"conditional" do %>

    <%= select_tag "countries", options_for_select(@countries.collect {|t| [t.state_name.to_s ,t.id]})  %>

    <%= select_tag "states", options_for_select(@states.collect {|t| [t.state_name.to_s ,t.id]}, params[:search].to_i ) %>

    <%= submit_tag "Search", :name => nil %>
<% end %>

I found something like this

  <%= collection_select :selection, :level, User::LEVELS, :to_s, :to_s, {},
     {:onchange => remote_function(
      :url => {:action => "updatelevel", :controller => "user", :id=> user.id},
      :with => "'level_id='+this.value"
    )
  }
  %>

I will appreciate help.


Solution

  • To list all the states belonging to a given country first set up the following relationship:

    class Country < ActiveRecord::Base
      has_many :states
    end
    
    class State < ActiveRecord::Base
      belongs_to :country
    end
    

    Then in the controller you can call all states like this:

    @country = Country.find(params[:id])
    @states = @country.states #this will be a hash of all states that belong_to @country
    

    and in the view, you can create a list like this (or use a table, depending on how you want it to be formatted):

    <ul>  
    <% @states.each do |state| %>
      <li>
        <%= state.name %>
      </li>
      #etc
    <% end %>
    </ul>