【问题标题】:RubyOnRails nested/dependent dropdown menuRubyOnRails 嵌套/依赖下拉菜单
【发布时间】:2011-10-05 19:24:04
【问题描述】:

我有一个带有 3 个下拉菜单的视图。 For example i have Country, State and City and in the view when the user select Country = US, then in the State dropdown it should populate a list of only US states, and when the state is selected the dropdown only need to bring up the该州属下的城市。我的数据库设置正确(State 有 state name 和 country_id 字段,City 有城市名称和 state_id)

我在视图中实现了以下内容,但这会给我带来所有记录,无论用户选择如何。

<div class="field">
  <%= f.label :sector, "Sector" %>
  <%= f.collection_select :sector_id, Sector.all, :id, :nombre, :prompt => false  %>
</div>
<div class="field">
  <%= f.label :municipio %>
  <%= f.collection_select :municipio_id, Municipio.all, :id, :nombre, :prompt => false  %>
</div>
<div class="field">
  <%= f.label :provincia %>
  <%= f.collection_select :provincia_id, Provincia.all, :id, :nombre, :prompt => false  %>
</div>

如何使这些下拉列表相互依赖?

【问题讨论】:

    标签: jquery ajax ruby-on-rails-3


    【解决方案1】:

    也许要尝试的一件事是添加一个选项,使其变为:

    <%= f.label :state%>
    <%= f.collection_select :country, :state_id, State.all, :id, :nombre, :prompt => false  %>
    </div>
    <div class="field">
    <%= f.label :city%>
    <%= f.collection_select :state, :city_id, City.all, :id, :nombre, :prompt => false  %>
    </div>
    

    collection_select 中的前三个选项是对象、方法、集合。所以这就像说,获取属于您的国家实例的状态 ID,并返回 State.all 返回的集合中的状态 ID。

    并确保您的模型设置正确:

    class State < ActiveRecord::Base
      belongs_to :country
    end
    class City < ActiveRecord::Base
      belongs_to :state
    end
    

    【讨论】:

    • 在尝试加载页面时,我得到了未定义的方法 `merge' for :nombre:Symbol。
    • 是的,很抱歉。我认为正在发生的事情是 rails 会自动将第一个选项设置为您在 f.label 方法中命名的内容,因此当您添加该新选项时,会有一个太多(我的错!)。这部分解释了为什么你会得到一个包含每个州/城市/国家的列表。该方法要求 Sector.all 返回的所有内容的扇区 ID
    • 这可能对你更有帮助。此示例看起来与您要查找的内容非常相似。 api.rubyonrails.org/classes/ActionView/Helpers/…
    • 。没有骰子,得到与以前相同的错误。可能值得一提的是,这个下拉字段正在另一个视图中实现。意味着它们都属于 servicio.rb 模型。
    猜你喜欢
    • 2018-03-27
    • 2014-07-03
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2011-11-21
    • 2019-04-23
    • 2016-10-13
    相关资源
    最近更新 更多