![](/img/trans.png)
[英]how to monitor instance variable from ruby controller pass to view html using AJAX
[英]Using AJAX to compare variable in Ruby and then render a view accordingly
我是javascript和ruby的新手,並且想知道我是否正在以正確的方式進行操作,以及如何獲得所需的結果。 我有一個名為events \\ new.html.erb的視圖,該視圖允許用戶在集合選擇中選擇另一個用戶:
<%= f.collection_select :id,
Customer.where(business_id: current_customer.business_id),
:id,
:full_name,
{ prompt: 'Select' },
{ id: "colleageselect", onChange: "renderColCal(this)" } %>
<div id = colleaguecal> </div>
這會觸發application.js中的javascript函數'renderColCal',我正在向ruby發送變量colleagueID:
function renderColCal(select){
var colleagueID = select.value ;
document.getElementById("colleaguecal").innerHTML = "Your colleague's calendar";
$.ajax({
url: 'calendars_controller/calendarChange',
data: (
'colleagueID=' + $('select').val()
)
}
)
}
這是我的路線:
post 'calendars_controller/calendarChange', to: 'calendars_controller#calendarChange'
然后在控制器“ calendars_controller”(不是events \\ new視圖的事件控制器)中,我嘗試使用colleagueID:
def calendarChange
colleagueID = params[:colleagueID]
colleague = Customer.where(id: :colleagueID )
@colcalendar = colleague.calendar
@events = @colcalendar.events
respond_to do |format|
format.js {render '/calendars/_showColleague'}
end
end
我想要做的是能夠使用Ruby的@events
變量在events\\new
html中呈現部分_showColleague
。 因此,每當用戶在集合選擇中選擇一個名稱時,它就會呈現所選同事的日歷視圖。 目前,使用此代碼我沒有任何反應。 請問我該怎么做? 我很新,不勝感激! 謝謝
這是我要做的:
#app/assets/javascripts/application.js
$(document).on("change", "select#id", function(e) {
$.get("colleagues/"+ + $(this).val() +"/calendars/1");
});
#config/routes.rb
resources :colleagues do
resources :calendars #-> url.com/colleagues/:colleague_id/calendars/:id
end
#app/controllers/calendars_controller.rb
class CalendarsController < ApplicationController
respond_to :js, :html
def show
@colleague = Customer.find params[:colleague_id]
@calendar = Calendar.find params[:id] #-> your pattern; not mine
@events = @colleague.calendar.events
end
end
#app/views/calendars/new.js.erb
$(".element").html("<%=j render 'calendars/_showColleague' %>");
-
這將使您可以使用返回的partial
來填充DOM,我認為這是您目前最大的問題。 還有其他一些注意事項(因為您是新手):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.