有没有办法在rails之间生成小于或大于查询,例如在范围之间查询。我有多个查询参数,因此我不想使用字符串文字进行比较。
if params["end_time"]
if params["start_time"]
params["end_time"] = params["end_time"].to_datetime
query[:created_at] = ((params["start_time"])..params["end_time"])
else
query[:created_at] = #Need help with this
end
end
答案 0 :(得分:0)
def with_duration
if(params['start_time'] && params['end_time'])
{created_at: params['start_time']..params['end_time']}
elsif(params['start_time'])
return ["created_at > ?", "#{params['start_time']}"]
elsif(params['end_time'])
return ["created_at < ?", "#{params['end_time']}"]
else
return {}
end
end
ModelName.where(with_duration)
答案 1 :(得分:0)
据我了解,如果params为空,你无需做任何事。所以你可以试试这个实现。
def query_method(scope)
return scope unless params["end_time"] && params["start_time"]
scope.where.not(created_at: (params["start_time"]..params["end_time"]))
end