Rails Postgresfunction索引
我应该如何将包含函数的多语言索引输入schema.rb?
例如,这不起作用:
add_index "temporary_events", ["templateinfoid", "campaign", "date(gw_out_time)", "messagetype"], :name => "temporary_events_campaign_tinfoid_date_messagetype"
rake db:test:load
耙子流产了!
PGError:错误:列“date(gw_out_time)”不存在
:CREATE INDEX“temporary_events_campaign_tinfoid_date_messagetype”ON“temporary_events”(“templateinfoid”,“campaign”,“date(gw_out_time”,“messagetype”)
用于创建索引的内置ActiveRecord方法( add_index
)不支持函数或任何其他更高级的function。 相反,您可以使用execute
来使用SQL创建索引:
execute <<-SQL CREATE INDEX temporary_events_campaign_tinfoid_date_messagetype ON temporary_events(templateinfoid, campaign, date(gw_out_time), messagetype); SQL
请注意,如果您不使用SQL架构格式( config.active_record.schema_format = :sql
),则在迁移中使用execute
可能会出现问题。 有关更多信息,请搜索schema_format 。
通过删除一对护栏,我能够从Rails(3.1.3)迁移中获得function索引!
# lib/functional_indexes.rb module ActiveRecord module ConnectionAdapters module SchemaStatements #disable quoting of index columns to allow functional indexes (eg lower(full_name) ) def quoted_columns_for_index(column_names, options = {}) column_names end def index_name_for_remove(table_name, options = {}) index_name = index_name(table_name, options) # disable this error check -- it can't see functional indexes #unless index_name_exists?(table_name, index_name, true) # raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist" #end index_name end end end end
我不得不制作自己的索引名称:
class AddLowerCaseIndexes < ActiveRecord::Migration def up add_index :people, 'lower(full_name)', :name => "index_people_on_lower_full_name" add_index :people, 'lower(company)', :name => "index_people_on_lower_company" end def down remove_index :people, :name => "index_people_on_lower_full_name" remove_index :people, :name => "index_people_on_lower_company" end end
(您可能不需要在索引列名称周围引用,除非您正在做一些疯狂的事情,例如在其中放置空格或奇怪的字符。)
(在尝试回滚不存在的索引时,你可能对postgres错误消息很好。)
如果您使用的是pg_power gem( https://github.com/TMXCredit/pg_power ),则可以通过以下方式执行此操作:
add_index(:comments, 'dmetaphone(author)', :using => 'gist')
- rails pg db for Devise Users的undefined方法`database_authenticatable’
- 你如何使用共享数据库在Heroku上进行GIS查询?
- 使用postgres在带轨道的DISTINCT ID中订购
- 在heroku上的PostgreSQL数据库中存储超过255个字符
- Ruby on Rails:有没有办法从数据库中提取项目并按指定顺序返回它们?
- PostgreSQL字符串(255)限制 – Rails,Ruby和Heroku
- 最好使用空值作为”还是NULL?
- RoR Postgresql时区组不在Heroku上工作
- 如何使用ActiveRecord访问Postgres列的默认值?