如何检查范围栏中是否存在参数

时间:2018-03-16 07:10:17

标签: ruby-on-rails activerecord scope

scope :created_after, ->(start_time,end_time) { where("start_time > ? and end_time <?", start_time,end_time) }

我想添加if条件,如果存在开始时间,那么只有start_time查询运行end_time然后运行其查询

2 个答案:

答案 0 :(得分:1)

我认为A = np.zeros([3,4,5]) idx = [1,3] B = # general command I am looking for B_bad = A[idx] # shape = (2,4,5), not what I want! B_manual = A[idx[0], idx[1]] # shape = (5), what I want, but as a general expression. # it is okay that the indexes are in order i.e. 0, 1, 2, ... 更适合您对created_between范围的处理。

您可以使用created_afterstart_time列创建两个帮助范围来过滤结果。

end_time

然后你可以按照你想要的方式组合它们:

scope :created_after, ->(start_time) do
  where("start_time > ?", start_time)
end

scope :created_before, ->(end_time) do
  where("end_time < ?", end_time)
end

如果对任何范围参数执行查询给出scope :created_between, ->(start_time, end_time) do query = self.all query = query.created_after(start_time) if start_time query = query.created_before(end_time) if end_time query end ,它将忽略它们。例如:nil将不会产生其他查询。

答案 1 :(得分:0)

你可以在条件

中链接它
scope :created_after, ->(start_time, end_time) { start_time && end_time && where("start_time > ? and end_time <?", start_time, end_time) }

仅当start_timeend_time存在

时,才会添加where条件