如何使用ajax更新我的lisbox?

时间:2013-09-27 17:32:04

标签: ruby-on-rails ruby ruby-on-rails-2

当我选择一个国家时,如何在我的搜索中创建一个ajax,它会显示我在所选国家/地区的所有州?

我正在尝试创建显示,当我选择国家/地区时会自动显示所有已选择国家/地区的状态

我的桌子

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

我的控制器

 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

我的观点

<% 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 %>

我找到了类似的东西

  <%= 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"
    )
  }
  %>

我将非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

要列出属于给定国家/地区的所有州,请首先设置以下关系:

class Country < ActiveRecord::Base
  has_many :states
end

class State < ActiveRecord::Base
  belongs_to :country
end

然后在控制器中你可以调用所有这样的状态:

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

并且在视图中,您可以创建这样的列表(或使用表格,具体取决于您希望如何格式化它):

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

答案 1 :(得分:0)

我在这里找到了一个非常简单的答案:

http://pullmonkey.com/2008/03/30/dynamic-select-boxes-ruby-on-rails/

非常实用且具有描述性。