[英]Rails Ajax Call to Controller Needs Record
我正在使用Rails ruby 6.1.4
和ruby 2.6.7
我有一個用於new
視圖和edit
視圖的部分表單。 有兩個select
下拉表單元素。 application.js
代碼對controller
進行Ajax
調用,以根據第一個下拉列表中選擇的內容獲取項目以填充第二個下拉列表。
對於new
視圖,我的代碼運行良好。 但是,在edit
視圖中查看記錄時,它不起作用。 在edit
視圖上時,路徑中似乎需要一個id
。
在我的瀏覽器中使用developer tools
時, console
window 在edit
視圖中顯示此錯誤:
[XHR] GET http://localhost:3000/fitness/weights/24/exercises?muscle_group=SHOULDERS
如您所見,它需要路徑中的id
。 但我不需要id
來獲得下拉練習。 當然,第二個下拉列表不會填充。
如何調整路線以使new
視圖和edit
視圖都能正常工作? 或者,我需要更改我的 ajax 通話嗎? 注意:當我將:exercises
移出路線中的collection
時,會發生相反的情況; new
表格不起作用,但edit
表格起作用。
這是我的代碼:
application.js:
// if edit view is showing
// get the current value of the Muscle Group field
//
var current_muscle_group;
if( $('#fitness_weight_muscle_group') ){
current_muscle_group = $('#fitness_weight_muscle_group').val();
}
if( current_muscle_group != '' && current_muscle_group != 'Select One' && current_muscle_group != null ){
get_exercises(current_muscle_group);
}
// user selects muscle_group from drop-down
// new or edit form
//
$('#fitness_weight_muscle_group').change(function(){
get_exercises($(this).val());
})
// get_exercises
// ajax call to controller#exercises
// to get exercies for the muscle_group
//
function get_exercises(current_muscle_group){
$.ajax({
url: "exercises",
dataType: "json",
data: {muscle_group: current_muscle_group},
success: function(data){
populate_exercise_select(data);
}
});
}
...
Controller
...fitness/weights/controller:
protect_from_forgery except: [:exercises, :past_exercise, :max_weight]
...
def exercises
# run sql to get exercises for muscle group passed in
if params[:muscle_group]
@exercises=Fitness::Weight.select("DISTINCT exercise")
.where(admin_user_id: session[:user_id])
.where(muscle_group: params[:muscle_group].upcase)
return render json: @exercises
end
...
我的路線
config/routes:
...
resources :weights do
collection do
get :exercises
...
end
end
...
換句話說,我們有一個 has_many 練習的肌肉組,(也許還有一個練習 has_many 肌肉組),如果它是一個雙向的 has_many,那么它是通過muscle_group has_and_belongs_to_many exercises
來實現的,反之亦然。
因此,要填充練習下拉列表,對於給定的肌肉組,我建議使用帶有索引方法的ExerciseController
控制器,該方法可以接受肌肉組 id 參數並使用練習列表響應 ajax 請求。
所以路線是:
resources :weights do
resources :exercises
end
和 controller:
class ExercisesController < ApplicationController
def index
@exercises = Exercise.joins(exercise_muscles: :muscles).where("muscles.id = ?", params[:muscle_id]
render @exercises # assumes a partial file '_exercise.html.erb' produces the option tag for an exercise dropdown
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.