我是 javascript 和 ruby 的新手,想知道我是否以正确的方式进行此操作,以及如何获得我想要的结果。 我有一个名为 events\new.html.erb 的 View ,它允许用户选择集合中的另一个用户选择:
<%= 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”,我将变量同事 ID 发送给 ruby:
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'
然后在 Controller “calendars_controller”(不是事件\新 View 的事件 Controller )中我尝试使用同事ID:
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
我想要做的是能够使用 @events
变量在 events\new
html 中渲染部分 _showColleague
ruby 。因此,每次用户在集合选择上选择一个名称时,它都会呈现所选同事的日历 View 。目前我使用此代码没有得到任何响应。请问我该怎么做呢?我很新,所以希望得到解释!谢谢
最佳答案
这就是我要做的:
#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,我认为这是您目前最大的问题。还有一些其他注意事项(因为您是新手):
您的路线应该是 RESTful (IE 的范围应围绕
calendar
对象)。您创建了一条超出范围的路由,该路由违反 convention .你的 JS 应该是 unobtrusive 。像您一样使用 JS(尤其是内联 JS)有一个习惯,就是由于 Turbolinks 而变得困惑。尽可能将JS放入asset pipeline .
find
= single ;where
= collection 。使用where
与 SQL 中的WHERE
子句相同 - 它返回多条记录。Find
始终返回单个记录;因此:阅读 nested routing 。您想要为
同事
加载日历
;您需要传递两个参数(目前还没有这样做)。
关于javascript - 使用 AJAX 比较 Ruby 中的变量,然后相应地渲染 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34874639/