Rails 动态/级联 Select 下拉列表

Rails Dynamic / Cascading Select dropdown list

我是一个相对初学者,一直在努力让它发挥作用。

在我的表格上,我想在 select 编辑了位置 (on_change) 后使用 Ajax 填充房间 select。

我大致遵循了这个 - https://kernelgarden.wordpress.com/2014/02/26/dynamic-select-boxes-in-rails-4/ - 但我不能完全让它工作。

表格

<%= form_for @booking do |form| %>
  <p>
    <%= form.label :booked_date %>
    <%= form.date_select :booked_date, order: [:month, :day, :year], start_year: 2018 %>
  </p>
  <p>
    <%= form.select :location_id, options_for_select(@locations.collect { |location| [location.name.titleize, location.id] }, 1), {}, { id: 'locations_select' } %>
  </p>
  <p>
    <%= form.select :room_id, options_for_select(@rooms.collect { |room| [room.name.titleize, room.id] }, 0), {}, { id: 'rooms_select' } %>
  </p>
  <p>
    <%= form.label :start_time %><br>
    <%= form.time_select :start_time %>
  </p>
  <p>
    <%= form.label :end_time %><br>
    <%= form.time_select :end_time %>
  </p>
  <p>
    <%= form.label :meeting_subject %><br>
    <%= form.text_field :subject %>
  </p>
  <p>
    <%= form.submit "Make this booking" %>
  </p>
<% end %>

bookings_controller

def update_rooms
    @rooms = Room.where("location_id = ?", params[:location_id])
    respond_to do |format|
      format.js
    end
  end

路线

Rails.application.routes.draw do
  root 'users#show'

  resources :users
  resources :bookings

  resources :locations do
    resources :rooms
  end


  resources :rooms do
    resources :bookings
  end

  get 'bookings/update_rooms', as: 'update_rooms'

end

update_rooms.JS

    $("#rooms_select").empty().append("<%= escape_javascript(render(:partial => @rooms)) %>")


bookings.js.coffee

$ ->
  $(document).on 'change', '#locations_select', (evt) ->
    $.ajax 'update_rooms',
      type: 'GET'
      dataType: 'script'
      data: {
        location_id: $("#locations_select option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic location select OK!")

部分rooms/_room.html.erb

<option value="<%= room.id %>"><%= room.name %></option>

当我 运行 页面并更改位置时 select 我收到此错误:

Started GET "/bookings/update_rooms?location_id=2&_=1536181850165" for 127.0.0.1 at 2018-09-05 22:10:52 +0100

AbstractController::ActionNotFound - The action 'show' could not be found for BookingsController:

Started GET "/bookings/update_rooms?location_id=1&_=1536181850166" for 127.0.0.1 at 2018-09-05 22:11:20 +0100

AbstractController::ActionNotFound - The action 'show' could not be found for BookingsController:

非常感谢任何帮助。

AbstractController::ActionNotFound - The action 'show' could not be found for BookingsController

问题是您指定的自定义路由与 bookingsshow 路由冲突。您需要将自定义路由放在 上方 resources :bookings 以避免该错误并将该路由映射到 update_rooms 操作

get 'bookings/update_rooms', as: 'update_rooms'
resources :bookings