【问题标题】:How to make the collection in a select input dependent on the value of another select input如何使选择输入中的集合依赖于另一个选择输入的值
【发布时间】:2014-11-28 17:02:47
【问题描述】:

我什至不知道从哪里开始,所以如果有人能指出我可能会有所帮助的潜在方向。

我的 Rails 应用程序中有一个带有两个选择输入的表单。

这是独立选择

<%= collection_select(:pass, :route_id, Route.all, :id, :name) %>

这是依赖选择

<%= collection_select(:pass, :afternoon_trip, Trip.all, :id, :departure) %>

现在,每条路线(来自独立选择)都有许多与之相关的行程。行程(相关)选择将所有行程显示为选项。

我只想在行程选择中显示属于所选路线的行程。关于如何做到这一点的任何想法?

当有人更改路线选择时,我还想更改行程选项,但这是次要问题。

谢谢!

【问题讨论】:

标签: ruby-on-rails forms simple-form


【解决方案1】:

我想你会想用一些 ajax 来解决这个问题。获取所选选项的 id,将其发送到您的控制器,然后根据控制器发回的数据呈现一个新菜单。伪代码和 coffeescript 可能如下所示:

# javascript
selectMenu = $('menu selectors')
selectMenu.mouseUp ->
  selectedId = // get menu's selected id
  $.ajax "path/to/populate_dependant?selected_id=" + selectedId


# controller
def populate_dependant
  id = params[:selected_id]
  @collection = Model.where(attribute: id)
  respond_to do |format|
    format.js {}
  end
end


# populate_dependant.js.erb
// write javascript to append the following to your form:
<%= f.label :model %>
<%= f.collection_select :model_id, @collection, :id, :attribute_name, :prompt => "Select something" %>

【讨论】:

  • 我想我在控制器中搞砸了...... def get_trips @route = Route.find(params[:route_id]) @trips = @route.trips respond_to do |format| format.js end end 当我包含这个 get_trips.js.erb $('.morning-trip-selection').empty(); $('.morning-trip-selection').append( $('&lt;option&gt;Select the trip&lt;/option&gt;')); &lt;% @trips.each do |trip| %&gt; $('.morning-trip-selection').append($('&lt;option value="&lt;#= trip.id %&gt;"&gt;&lt;%= trip.departure_time %&gt;&lt;/option&gt;')); &lt;% end %&gt; 我得到未定义的方法 `each' 为 nil :NilClass 错误
  • 听起来@route.trips 返回 nil,这意味着您正在测试的路线没有关联的行程。确保正确填写变量。您可以尝试在您的控制器中窥探以查看您的 params@route@trips 的最终值。 github.com/pry/pry
【解决方案2】:

mouseUp 事件在 Steel 的回答中不起作用,并且不清楚如何重新加载页面。以下对我有用。假设菜单所在的页面是trips控制器的show动作。

咖啡脚本是

selectMenu = $('#route_select')
  selectMenu.change ->
    selectedID = $('#route_select :selected').text()
    $.ajax "/trips/populate_dependant?selected_id=" + selectedId

populate_dependant 更改为

def populate_dependant
  id = params[:selected_id]
  session[:collection] = Model.where(attribute: id)
  respond_to :js
  render :populate_dependant
end

这会将集合存储在会话中。然后在控制器的视图中创建一个新的咖啡脚本页面。

#app/views/trips/populate_dependent.coffee.erb
 window.location.reload();

这会重新加载原始页面。然后将以下内容添加到show 操作中

def show
  ...
  @collection = session[:collection]
  ...
end

如果使用 turbolinks,这会很快工作。

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 2022-01-15
    • 2020-10-09
    • 1970-01-01
    • 2021-09-18
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多