Avoid superfluous transaction when saving drafts

This commit is contained in:
Sam 2013-10-02 12:17:27 +10:00
parent 30bedff2c9
commit 5f8851cb44
2 changed files with 16 additions and 4 deletions

View File

@ -7,12 +7,10 @@ class Draft < ActiveRecord::Base
d = find_draft(user,key)
if d
return if d.sequence > sequence
d.data = data
d.sequence = sequence
d.update_columns(data: data, sequence: sequence)
else
d = Draft.new(user_id: user.id, draft_key: key, data: data, sequence: sequence)
Draft.create!(user_id: user.id, draft_key: key, data: data, sequence: sequence)
end
d.save!
end
def self.get(user, key, sequence)

View File

@ -11,6 +11,20 @@ class ActiveRecord::Base
exec_sql(*args).cmd_tuples
end
# note: update_attributes still spins up a transaction this can cause contention
# this method performs the raw update sidestepping AR
def update_columns(hash)
sql = "UPDATE #{ self.class.table_name } SET "
sql << hash.map do |k,v|
"#{k} = :#{k}"
end.join(",")
sql << " WHERE id = :id"
exec_sql(sql, hash.merge(id: self.id))
end
def exec_sql(*args)
ActiveRecord::Base.exec_sql(*args)
end