148
95

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで2つ以上の値の組み合わせに対するユニーク制約をかける

Last updated at Posted at 2013-02-20

例えばLikeの実装で例えば1つの記事に対しては1ユーザー当たり1回しかLikeできないとします。
つまり、(article_id, user_id)の組み合わせはユニークでなくてはなりません。
そういったときのvalidationの書き方は以下のようにかなりシンプルに書くことができます。

like.rb
class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :article

  validates :user_id, :uniqueness => {:scope => :article_id}
end
148
95
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
148
95

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?