Skip to content

Instantly share code, notes, and snippets.

@yn-misaki
Created May 15, 2017 11:07
Show Gist options
  • Save yn-misaki/a69891c94b44f8626afcab4be2225b2c to your computer and use it in GitHub Desktop.
Save yn-misaki/a69891c94b44f8626afcab4be2225b2c to your computer and use it in GitHub Desktop.
ユニーク制約を貼ってないテーブルで、ActiveRecord::RecordNotUniqueエラーを発生させる ref: http://qiita.com/yn-misaki/items/bf84996c03570d5de07e
after_create do
# これで発行されるSQLではNG!
if Post.where(user_id: self.user_id, title: self.title).count > 1
raise ActiveRecord::RecordNotUnique.new(self)
end
end
after_create do
# lockメソッドを使う
if Post.lock.where(user_id: self.user_id, title: self.title).count > 1
raise ActiveRecord::RecordNotUnique.new(self)
end
end
class Post < ActiveRecord::Base
after_create do
if Post.where(user_id: self.user_id, title: self.title).count > 1
raise ActiveRecord::RecordNotUnique.new(self)
end
end
end
SELECT * FROM posts FOR UPDATE
class UserController
def create
begin
User.create!(user_id: <user_id>, title: <title>)
rescue ActiveRecord::RecordNotUnique
head :conflict
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment