使用 rails 4.
我有一个 Spot
模型,一周中的每一天都有 7 个 bool 属性:monday:boolean
、tuesday:boolean
、wednesday:boolean
等
用户应该能够选择一个日期范围,并且只返回那些日子可用的景点。
目前在设置查找正确记录的类方法时遇到问题。
到目前为止,我正在根据用户输入的日期创建一个范围,它会返回该范围内一周中的所有日期。
range_array = (start_date..end_date).to_a.map{ |date| date.strftime("%A").downcase }
=> ["wednesday", "thursday", "friday"]
这就是我卡住的地方。我试图找到与数组中的元素对应的 bool 字段为真的所有点。所以在上面的例子中,我想形成这个查询 Spot.where(wednesday: true, thursday: true, friday: true)
这样的事情可行吗?有更好/不同的方法吗?也许我做错了。感谢您的帮助/建议。
更新(对于安德烈)... Spot.first
示例实例:
=> #<Spot id: 18, address: "4640 east skyline", title: "iodjiojoidj", description: "<p>jijiojfojewoif</p>\r\n",
created_at: "2016-03-30 04:54:07",
updated_at: "2016-09-26 05:39:51",
user_id: 13, timezone: nil,
surge_pricing: nil, free: nil, monday: true,
tuesday: true, wednesday: true, thursday: false,
friday: false, saturday: false, sunday: false>
最佳答案
使用您的range_array
,您应该能够按如下方式进行查询:
query = range_array.inject({}) do |h, e|
h[e] = true
h
end
Spot.where(query)
关于ruby-on-rails - 记录数组的每个元素的 bool 值为真 - Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40670710/