![](/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.