我需要在View中显示一些元素,然后根据用户选择过滤它们。我试图将控制器结果中的变量与javascript变量进行比较,但在这种情况下似乎不可能。
我有以下型号:
create_table "appointments", force: true do |t|
t.integer "doctor_id"
t.integer "user_id"
t.datetime "start_date"
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "end_date"
end
在我的控制器中,我有这个来获得所有约会:
@appointments = Appointment.all
现在在我的视图中,我显示所有约会:
events:
[
<% @appointments.each do |appointment| %>
{
id : "<%= appointment.id %>",
title : "Reserved",
start : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
end : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
allDay : false
},
<% end %>
],
这完全有效,但我有一个选项,用户可以选择医生,只应出现该医生的预约。我怎么能做到这一点?我试图像这样过滤它们,但它不起作用:
events:
[
<% @appointments.each do |appointment| %>
if <%= appointment.doctor_id %> == doctor_id{
{
id : "<%= appointment.id %>",
title : "Reserved",
start : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
end : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
allDay : false
},
}
<% end %>
],
谢谢大家。
答案 0 :(得分:1)
修改:要使用选择框仅为一位医生预约,请在选择框中选择选项时首先发送ajax请求:
$("select").change(function() {
$.ajax({
type: 'POST',
data: 'selected=' + $("select option:selected").text(),
dataType: 'json',
success: function(data) {
if ($.trim(data) !== '') {
// data should be the returned json of all the appointments for only the selected doctor. Do whatever you want with it.
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
},
url: <insert post route here>
})
});
这就是控制器操作的样子:
def retrieve_doctor_id
selected_doctor = Doctor.find(params[:selected])
@appointments = selected_doctor.appointments.select([:id, :start_date, :end_date])
respond_to do |format|
format.json render :partial => "your_controller/retrieve_doctor_id", :locals => {:appointments => @appointments}
end
end
文件:app / views / your_controller / retrieve_doctor_id.json.erb:
events:
[
<% appointments.each do |appointment| %>
{
id : "<%= appointment.id %>",
title : "Reserved",
start : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
end : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
allDay : false
},
<% end %>
],
我没有对此进行过测试,请告诉我是否有任何错误或问题。
答案 1 :(得分:0)
这样的事情应该有效
events:
[
<% @appointments.select { |a| a.doctor_id == @doctor_id }.each do |appointment| %>
{
id : "<%= appointment.id %>",
title : "Reserved",
start : "<%= appointment.start_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
end : "<%= appointment.end_date.in_time_zone.strftime '%Y-%m-%dT%H:%M:%S' %>",
allDay : false
},
<% end %>
],
假设@doctor_id
是您要过滤的医生的ID。但是,我必须评论这种做法真的很混乱。您应该使用json构建器,例如rabl。