Rails ActiveRecord 有没有支持分表的办法?

heliang7 · July 25, 2013 · Last by mingyuan0715 replied at February 22, 2016 · 3749 hits

大概有这样一类表,结构都是相同的

sample_data_12222
sample_data_12223
sample_data_12224
sample_data_12225

问题是这类表有 3000 多张。 先前我的想法是有多少表就用多少模型的办法

ActiveRecord::Base.connnection.tables.grep(/sample_data_\d+/).each
  Class.new(ActiveRecord::Base) do
  ...
  end
end

但是数量过多,启动后 rails 就没有反应了。

现在我的想法是用 set_table_name 来运行时改变表的指向。用 find 的时候,好像没问题,但是用 where 的时候,返回一个 Active::Relation,把它直接转变为 json 的时候

SampleData < ActiveRecord::Base

  def some
    where(...)
  end

end

some = SampleData.some #some is now Active::Relation object

render json: {data: some}  #here will generate sql below

会生成 sql 语句

select `sample_data_12223`.* from `sample_data_12222' where ...

这样的查询,当然就失败了。

当然解决办法很简单

def some
  where(...).all #now return SampleData
end

但是感觉也不太优雅。

我想请教下大家有没有比较优雅的解决这个问题的办法?

这个应该是数据库层面处理的,不需要 rails 介入。不过在写查询的时候注意下,分表的键必须带在查询里。

You need to Sign in before reply, if you don't have an account, please Sign up first.