如何从该数据库记录中返回键值对true
。今天早上似乎没办法喝,可能需要更多咖啡。
这是我的代码:
def get_enabled_speeds_from_db
@speed_details = []
current_speeds.each do |speed|
@speed_details << shop.speeds.find_by(shipping_speed: speed)
end
end
在上面的方法current_speeds
中只是一个列出了速度的数组,它看起来像这样:
["Standard", "Expedited"]
方法完成后,speed_details
如下所示:
[#<Speed id: 51, shipping_speed: "Standard", fixed: false, fixed_amount: nil, flex: true, flex_dollar_or_percent: "$", flex_amount: #<BigDecimal:411ebb8,'0.1E2',9(18)>, free: false, free_shipping_amount: nil, created_at: "2018-07-11 18:39:17", updated_at: "2018-07-11 18:39:17", store_id: 15, enabled: true>, #<Speed id: 52, shipping_speed: "Expedited", fixed: true, fixed_amount: #<BigDecimal:3f6e2a0,'0.1E2',9(18)>, flex: false, flex_dollar_or_percent: "", flex_amount: nil, free: true, free_shipping_amount: 25.0, created_at: "2018-07-11 18:39:46", updated_at: "2018-07-11 18:39:46", store_id: 15, enabled: true>]
现在,我要做的就是通过speed_details
来拉出设置为true
的键/值对。例如,在speed id:51
flex: true
和enabled: true
中。在speed id: 52
中,fixed
是true
。
这是我执行此操作的方法,但不能在select
上使用speed
。我尝试过更改为数组和枚举,但我需要键/值对,而不仅仅是真存在。
def get_enabled_speed_details_that_are_true
speed_details.each do |speed|
speed_name = {speed: speed[:shipping_speed]}
whats_turned_on = speed.select{|k,v| v == true }
walk_thru_each_rate_type(speed_name.merge(whats_turned_on))
end
end
有什么建议吗?
答案 0 :(得分:1)
您可能首先希望只获取其值为布尔值的字段,即只能为true / false,然后从中进行过滤。
final_result = []
Model.select('field1, field2, field3').each do |model|
current_matching_result = model.attributes.collect{|key,value| key if value ==true}
if current_matching_result.compact.present?
truthy_array = [true] * current_matching_result.count
filtered_attributes_hash = current_matching_result.zip(truthy_array).to_h.merge!({id: model.id})
final_result << filtered_attributes_hash
end
end