Created
May 15, 2017 11:07
-
-
Save yn-misaki/a69891c94b44f8626afcab4be2225b2c to your computer and use it in GitHub Desktop.
ユニーク制約を貼ってないテーブルで、ActiveRecord::RecordNotUniqueエラーを発生させる ref: http://qiita.com/yn-misaki/items/bf84996c03570d5de07e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT * FROM posts FOR UPDATE |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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