我是一个相对初学者,一直在努力使它生效。
在我的表单上,一旦选择了位置(on_change),我想使用Ajax填充“房间”选择。
我大致遵循了这个原则-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!")
部分房间/_room.html.erb
<option value="<%= room.id %>"><%= room.name %></option>
当我运行页面并更改位置时,选择此错误:
开始获取GET“ / bookings / update_rooms?location_id = 2&_ = 1536181850165” 127.0.0.1 at 2018-09-05 22:10:52 +0100
AbstractController :: ActionNotFound-动作“显示”不能为 找到BookingsController:
开始获取GET“ / bookings / update_rooms?location_id = 1&_ = 1536181850166” 127.0.0.1 at 2018-09-05 22:11:20 +0100
AbstractController :: ActionNotFound-动作“显示”不能为 找到BookingsController:
非常感谢任何帮助。
答案 0 :(得分:1)
AbstractController :: ActionNotFound-动作“显示”不能为 找到BookingsController
问题是您指定的自定义路由与show
的{{1}}路由冲突。您需要将自定义路线放在上方 bookings
以避免该错误,并将该路线映射到resources :bookings
操作
update_rooms