【发布时间】:2015-12-20 20:01:27
【问题描述】:
我有一张表,其中有许多其他字段之一hstore
db/schema.rb
create_table "requests", force: true do |t|
t.hstore "parameters"
end
一些记录有一个字段parameters["company_id"],但不是全部。
我需要做的是确保只使用给定的parameters["company_id"] 创建一个Request 对象。可能有多次尝试同时保存记录 - 因此是竞争条件。
我正在整个表格的 hstore 中寻找唯一的 company_id 值。
我发现我可以运行一个事务来锁定数据库并检查给定parameters["company_id"] 的请求是否存在,如果不创建它。如果company_id 是Request 模型上的一个简单字段,我可以这样做:
Request.transaction do
if Request.find_by(company_id: *id* )
log_duplication_attempt_and_quit
else
create_new_record
log_successful_creation
end
end
不幸的是,它是hstore,我无法更改它。使用hstore 实现这一目标的最佳方法是什么?
我正在寻找快速的东西,因为表中有很多记录。 纯 SQL 查询是可以的 - 不幸的是我没有足够的 SQL 背景来弄清楚我自己。 可以为性能编制索引吗?
示例:
a = Request.new(parameters: {company_id: 567, name: "John"})
b = Request.new(parameters: {name: "Doesn't have company_id in the hstore"})
c = Request.new(parameters: {company_id: 567, name: "Galt"})
a.save // valid success
b.save // valid success even if company_id hasn't been provided
c.save // not valid Request with company_id 567 already in the table
【问题讨论】:
标签: ruby-on-rails postgresql database-design hstore unique-index