我不喜歡傳遞多個重復的引數,它看起來有點難看。
我該如何重構以下代碼?
prev_month_start = Date.today.prev_month.beginning_of_month
prev_month_end = Date.today.prev_month.end_of_month
contacts = contacts.where('
persons.actual_delivery_date >= ? AND persons.actual_delivery_date <= ? OR
persons.expected_shipment_date >= ? AND persons.expected_shipment_date <= ?',
prev_month_start, prev_month_end,
prev_month_start, prev_month_end)
uj5u.com熱心網友回復:
在此類情況下,您可以將日期范圍 ( all_month) 與or條件結合使用:
prev_month = Date.today.prev_month.all_month
contacts = contacts
.where(persons: { actual_delivery_date: prev_month })
.or(contacts.where(persons: { expected_shipment_date: prev_month }))
uj5u.com熱心網友回復:
您可以在 ActiveRecord 5 及更高版本中嘗試類似的操作:
contacts.where(actual_delivery_date: prev_month_start..prev_month_end).or(expected_shipment_date: prev_month_start..prev_month_end)
https://guides.rubyonrails.org/active_record_querying.html#range-conditions
根據評論編輯
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536892.html
