所以我有一个User
模型,我希望能够做的就是有一个可用的预约时间列表,让用户在注册时选择其中一个。我在脑海中设想我会有一些TimeSlotList,它会在两个DateTime实例之间以xxx分钟为增量生成TimeSlots,然后让User有一个TimeSlot作为属性?也许每个TimeSlot都有一个taken
布尔值,表示用户是否已经接受了它?
有没有某种标准方法可以做这样的事情?我无法想象这实现功能的情况太少了。
答案 0 :(得分:5)
虽然我确信这个地方会有一颗宝石,但我会看看能不能给你答案:
<强>方法强>
处理此问题的两种方法如下:
time_1
&amp; time_2
),直接从输入中创建Application
对象TimeSlots
(使“时间”无关紧要),并将Application
对象与TimeSlot
<强> Time.parse 强>
你可以做的第一种方法是手动解析时间。我这样做:
#app/models/appointment.rb
Class Appointment < ActiveRecord::Base
belongs_to :user
end
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :appointments
def valid?
taken = where("start <= ? AND end >= ?", start, end)
save unless taken
end
end
appointments
id | user_id | start | end | created_at | updated_at
users
id | etc | etc | created_at | updated_at
#app/controllers/appointments_controller.rb
def new
@appointment = Appointment.new
end
def create
#Validate
@appointment = Appointment.new(appointment_params).valid?
end
private
def appointment_params
params.require(:appointment).permit(:start, :end).merge(user_id: current_user.id)
end
<强>时隙强>
如果你打算使用预定义的TimeSlots,你可以这样做:
#app/models/time_slot.rb
Class TimeSlot < ActiveRecord::Base
has_many :appointments
has_many :users, through: :user_time_slots
end
#app/models/appointment.rb
Class Appointment < ActiveRecord::Base
belongs_to :time_slot
belongs_to :user
def valid?
taken = where(day: day, time_slot_id: time_slot_id)
save unless taken
end
end
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :appointments
has_many :time_slots, through: :appointments
end
time_slots
id | name | time | duration | etc | etc | created_at | updated_at
appointments
id | user_id | time_slot_id | day | created_at | updated_at
users
id | etc | etc | etc | created_at | updated_at
这将允许您创建一个系统,以便用户可以使用特定的TimeSlots。不同之处在于,您需要在Appointment
模型上对TimeSlot
&amp; day
已被采取:
#app/controllers/appointments_controller.rb
def new
@appointment = Appointment.new
end
def create
#Validate
valid = Appointment.new(appointment_params).valid?
#Response
respond_to do |format|
if valid
format.html { redirect_to success_url }
format.js
else
format.html { redirect_to failure_url }
format.js
end
end
end
private
def appointment_params
params.require(:appointment).permit(:time_slot_id, :day).merge(user_id: current_user.id)
end
您可以通过在数据库中使用某些索引来优化此操作,以防止相同的day
&amp;正在使用time_slot
答案 1 :(得分:1)
您可以在显示所有时段时使用TimeSlotManager
类别排序,以及现有约会
class Appointment < ActiveRecord::Base
# :to_time
# :from_time
# :on_date
end
class TimeSlotManager
def initialize(date, appointments)
@date = date
@appointments = appointments
end
def slots
# generate slots
# pass appropriate appointment if time slot within appointment range
end
end
def TimeSlot
def initialize(from_time, to_time, appointment=nil)
@from_time = from_time
@to_time = to_time
@appointment = appointment
end
attr_accessor :from_time, :to_time, :appointment
end
你至少那时只记录实际的约会。