我问过一个关于具有验证重叠here的作用域的问题,但是这个问题使代码更进一步,还有一个不同的问题涉及一个条件范围(可能称为其他内容)。
我的应用程序简介(在其他问题中也有描述)。我正在创建一个预订应用程序,并使用验证重叠宝石,我想确保没有重叠的预订同一房间。有两个房间。他们都可以同时预订。
到目前为止,其他问题和当前代码的解决方案如下:
class Booking < ActiveRecord::Base
scope :confirmed_scope, -> {confirmed: true}
validates :start_time, :end_time, :overlap => {
:exclude_edges => ["starts_at", "ends_at"],
:scope => "studio_id",
:query_options => {:confirmed_scope => nil}
}, on: :update
end感谢帮我找出了这个长度的范围。
按照这个代码,房间不能同时预定。
但是仍然存在一个问题,工人和客户仍然可以同时预订两个房间,这并不理想(因为,很明显,人们不可能同时在两个地方)。一个客户和一个工人不会故意为自己订票两次,但我觉得最好让他们确认一下,以确保一个员工不会意外地与两个不同的客户预订(在两个不同的房间,这是可能的)。
由于上面没有向worker_id或client_id查询,所以只有在该房间可用的情况下才允许预订。它不在乎是谁在做预订。
我需要添加一个“条件范围”,以检查正在预订的client_id或worker_id是否已经在另一个房间同时预订。
我尝试了以下代码:
:scope => ["studio_id","worker_id","client_id"], {...}但是,这将标志一个验证,现在,如果有一个在该工作室与该工作人员与该客户,使重复预订允许的工作室。
理想情况下,预订只能在房间可用的情况下进行,如果有,请检查一下,以确保尝试预订的工作人员目前已在另一个房间预订。如何修改我的作用域以检查上述条件?
希望我的问题是清楚的,请告诉我,如果有什么不清楚或是否需要更多的信息。Update:我认为提供的解决方案几乎是我所需要的,但是将studio_id保持在它所在的位置,并将worker和client id包含在一个单独的作用域中。
这样的代码为2获得了一个参数错误1:
scope :includes_studio_worker_client, -> (client_id, engineer_id) { where('engineer_id = ? OR client_id = ?', engineer_id, client_id) }
validates :start_time, :end_time, :overlap => {
:scope => "studio_id",
:query_options => {
:confirmed_scope => nil,
:includes_studio_worker_client =>
proc{ |booking| [booking.engineer_id, booking.client_id] }
},
:exclude_edges => ["start_time", "end_time"]
}发布于 2014-10-26 07:41:03
更新:我想,我现在明白你的问题了。您需要的不是搜索时间重叠的条目,而是具有相同的"studio_id“、"worker_id”和"client_id“的条目。但您需要搜索与时间重叠且具有相同的"studio_id“或"worker_id”或"client_id“的条目。是对的吗?
将传递为:scope选项的所有内容都将与"AND“连接起来。因此,您需要为每个属性编写验证。
结果代码如下所示:
class Booking < ActiveRecord::Base
scope :confirmed, -> {where(confirmed: true)}
validates :starts_at, :ends_at, :overlap => {
:exclude_edges => ["starts_at", "ends_at"],
:query_options => {:confirmed => nil},
:scope => 'client_id',
:message_content => 'is already taken in this time',
:message_title => 'Client '
}, on: :update
validates :starts_at, :ends_at, :overlap => {
:exclude_edges => ["starts_at", "ends_at"],
:query_options => {:confirmed => nil},
:scope => 'worker_id',
:message_content => 'is already taken in this time',
:message_title => 'Worker '
}, on: :update
validates :starts_at, :ends_at, :overlap => {
:exclude_edges => ["starts_at", "ends_at"],
:query_options => {:confirmed => nil},
:scope => 'studio_id',
:message_content => 'is already taken in this time',
:message_title => 'Studio '
}, on: :update
end顺便说一句。下面是如何在rails 4 scopes with lambda and arguments in Rails 4 style?中编写作用域
https://stackoverflow.com/questions/26569783
复制相似问题