所以我有一个User模型,以及所有我希望能够做的是有可用约定时隙的列表,并让用户自己注册过程中选择其中之一.我在脑海中想象我会有一些TimeSlotList,它会在两个DateTime实例之间以xxx分钟为增量生成TimeSlots,然后让User有一个TimeSlot作为属性?也许每个TimeSlot都有一个taken布尔值,表明用户是否已经使用它?
有什么标准方法可以做这样的事情吗?我无法想象这实现功能的情况并不常见.
虽然我确信这个地方会有一颗宝石,但我会看看能不能给你答案:
方法
处理此问题的两种方法如下:
time_1&time_2),Application直接从输入创建对象TimeSlots(使"时间"无关),并将Application对象与a 关联TimeSlotTime.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
Run Code Online (Sandbox Code Playgroud)
时隙
如果您要使用预定义的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
Run Code Online (Sandbox Code Playgroud)
这将允许您创建一个系统,以便用户可以使用特定的TimeSlots.的区别是你必须验证的Appointment模型,对TimeSlot与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
Run Code Online (Sandbox Code Playgroud)
您可以通过使用数据库中的某些索引来优化此操作,以防止相同day和time_slot正在使用
| 归档时间: |
|
| 查看次数: |
3577 次 |
| 最近记录: |