1

考虑这张表:

create_table "liquor_lots", force: :cascade do |t|
  t.integer "recipe_id"
  t.datetime "created_at", precision: 6, null: false
  t.integer "counter"
end

以及由此产生的模型

class LiquorLot < ApplicationRecord
 def lotcode
    "#{recipe_id}#{created_at.strftime("%y")}#{created_at.strftime("%W")}#{created_at.strftime("%u")}"
  end
  
  def pallet_lotcode
    "#{lotcode}-#{counter}"
  end
end

我想在 SQL 中做同样的事情: Select distinct(lotcode) from liquor_lots

我已经尝试过了,它失败是可以理解的,因为lotcode它不是桌子上的一列liquor_lots。但我一直被建议不要添加列来存储从其他列中的数据派生的数据。

那么如何搜索这些值呢?

对于上下文,我lotcode实际上由更多的值串联在一起组成,为了便于阅读,我在示例中只限制了三个值。

4

2 回答 2

1

据我所知,使用基本的 ActiveRecord 你无法做到这一点。ActiveRecord 必须对您的 ruby​​ 代码了解太多。

您可以实现一个手动连接相关值的 SQL 查询(请参阅对您问题的评论)。

或者,您可以查询所有对象(或仅使用 查询相关值pluck()),然后使用标准 Ruby Array/Enumerable 方法(在内存中)进行处理。如果应用程序不是性能关键的,很少发生,并且您没有数千个 Liquor_lots,那么在我看来,这将是一个不错的生产力权衡。

除了将其存储在自己的列中之外,您还可以将代码提取到单独的表中并创建PalletLotcode自己的实体。LiquorLots会比belong_to一个单一的PalletLotcode哪个会have_many LiquorLots。但与单独的列相比,这是一个相当复杂的操作,但如果要将其他信息存储在 Lotcodes 上,则很有意义。

于 2020-11-18T06:25:50.347 回答
-1

您可以尝试以下方法:

LiquorLot.where("recipe_id = :rcp_id AND created_at >= :begin_of_day AND created_at <= :end_of_day", {begin_of_day: calculate_begin_of_day, end_of_day: calculate_end_of_date, rcp_id: id})

calculate_begin_of_daycalculate_end_of_date可以使用Date.comercial方法和 Date.beginning_of_day 和 Date.end_of_day来实现

于 2020-11-18T04:03:34.237 回答