我是Ruby的新手。我有创建新约会的表单(我保存doctor_id
,patient_id
,date
,time
)我还有数据库中的日程安排(doctor_id
日程安排是FK
,有dayofweek
,starttime
,endtime
),现在我想查看医生是否在所选日期和时间可用,以及是否没有约会此日期和时间。如果我无法添加和错误消息。
翻译以便您更好地理解:
-dzien_tygodnia - day_of_the_week;
-data_wizyty - visit_date;
-godzina_wizyty - visit_time;
-poczatek_pracy - start_working;
-koniec_pracy - end_working.
我的_form.html.erb
:
<%= form_for(@appointment) do |f| %>
<% if @appointment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@appointment.errors.count, "error") %> prohibited this appointment from being saved:</h2>
<ul>
<% @appointment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :data_wizyty %><br />
<%=
options = { start_year: 2.year.from_now.year,
end_year: 2013,
include_blank: true,
default: nil }
f.date_select :data_wizyty, options
%>
<!--<input type="text" data-behaviour='datepicker' :data_wizyty > -->
</div>
<div class="field">
<%= f.label :godzina_wizyty %><br />
<%= f.time_select :godzina_wizyty %>
</div>
<div class="field">
<%= f.hidden_field :doctor_id, :value => Doctor.find(session[:current_doctor_id2]).id %>
</div>
<div class="field">
<%= f.hidden_field :patient_id, :value => Patient.find(session[:current_patient_id]).id %>
</div>
<div class="actions">
<%= submit_tag "Utworz wizyte" %>
</div>
<% end %>
appointment.rb
:
class Appointment < ActiveRecord::Base
validates :doctor_id, uniqueness: { scope: [:data_wizyty, :godzina_wizyty], message: 'Ten termin jest juz zajety!' }
validate :doctor_is_scheduled
attr_accessible :data_wizyty, :doctor_id, :godzina_wizyty, :notatka, :objawy_choroby, :patient_id
belongs_to :patient
belongs_to :doctor
belongs_to :schedule
belongs_to :refferal
has_many :employees
def doctor_is_scheduled
if Schedule.where(doctor: doctor, dzien_tygodnia: data_wizyty.wday)
.where('poczatek_pracy < ? and koniec_pracy > ?', godzina_wizyty, godzina_wizyty).empty?
self.errors.add(:doctor, message: 'nie pracuje w tym terminie!')
end
end
end
你能告诉我应该包含哪些文件吗?
答案 0 :(得分:3)
您在这里寻找的是validations。给Rails指南一个阅读,因为它对你非常有帮助。至于你的问题,你应该能够使用以下内容:
class Appointment < ActiveRecord::Base
validates :doctor_id, uniqueness: { scope: [:date, :time], 'already has an appointment at that time' }
validate :doctor_is_scheduled
def doctor_is_scheduled
if Schedule.where(doctor: doctor, dayofweek: date.wday)
.where('starttime < ? and endtime > ?', time, time).empty?
self.errors.add(:doctor, 'is not scheduled to be working at that time')
end
end
end
第一行(validates :doctor_id, uniqueness:
)检查在给定的日期和时间,医生是唯一的,即医生不会被双重预订。 doctor_is_scheduled
方法检查给定的医生和一周中的某一天,医生是否安排了班次(starttime
和endtime
之间)。