在我的 Ruby on Rails 应用程序中,我有一个模型 Message
,它有一个 created_at
列和一个 status_updated_at
列。它们都是日期时间。
为了加快查询速度,例如 Message.where(status: 'delivered', account_id: 11).where('status_updated_at - created_at >= ?', "180 seconds")
,我想为列 status_updated_at
和 created_at
之间的差异添加索引。
我试过这段代码:
class AddMessageIndicesForDashboard < ActiveRecord::Migration[5.1]
def change
add_index :messages, [:status, :account_id, :created_at, "(status_updated_at-created_at)"], name: 'dashboard_delivery_time_index'
end
end
这导致 PG::UndefinedColumn: ERROR: column "status_updated_at-created_at"does not exist
奇怪的是,假设我只想通过执行 add_index :messages, "(status_updated_at-created_at)", name: 'dashboard_delivery_time_index'
将索引添加到 status_udpated_at - created_at
,它将起作用。
有什么建议吗?谢谢!
最佳答案
也许试试
add_index :messages, "(status_updated_at-created_at)", name: 'dashboard_delivery_time_index'
PostgreSQL(9.1) 11.7. Indexes on Expressions .
The syntax of the CREATE INDEX command normally requires writing parentheses around index expressions... The parentheses can be omitted when the expression is just a function call...
因为你想使用表达式而不是函数,所以额外的括号应该根据文档来完成。
关于ruby-on-rails - Rails 迁移以添加索引到 2 列之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484722/