I have a table which has amongst many other fields one hstore
db/schema.rb
create_table "requests", force: true do |t|
t.hstore "parameters"
end
Some of the records have a field parameters["company_id"]
but not all of them.
What I need to do is to make sure that only one Request
object is created with a given parameters["company_id"]
. There might be multiple attempts trying to save a record at the same time - thus the race condition.
I am looking for unique company_id
values inside the hstore
across the table.
I figure out that I could run a transaction to lock the database and check if the request with given parameters["company_id"]
exist end if not create it. If company_id
would be a simple field on a Request
model I could do something like this:
Request.transaction do
if Request.find_by(company_id: *id* )
log_duplication_attempt_and_quit
else
create_new_record
log_successful_creation
end
end
Unfortunately it is hstore
and I can't change it. What would be the best way to achieve this with hstore
?
I am looking for something fast as there are a lot of records in a table. Pure SQL query is OK - unfortunately I don't have enough SQL background to figure it out my self. Can this be indexed for performance?
Example:
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