LoginSignup
23
21

More than 5 years have passed since last update.

rails4でhas_manyにuniq制約を付ける

Last updated at Posted at 2014-05-27

railsでhas_many :throughした時に重複しないような制約をかけるために、従来は以下のようにしていました。

product.rb
class Product < ActiveRecord::Base
  has_many :product_categories
  has_many :categories, through: product_categories, uniq: true
end

ですが、これだとRails4.xでは以下のようなdeprecation warningが出ます。

DEPRECATION WARNING: The following options in your Product.has_many :categories declaration are deprecated: :uniq. Please use a scope block instead. For example, the following:
(以下略)

この警告をなくすにはscopeを使って以下のように書きます。

product.rb
class Product < ActiveRecord::Base
  has_many :product_categories
  has_many :categories, -> { uniq }, through: product_categories
end

現時点では以前の書き方でも動きますが将来のバージョンでは無効になるので今のうちに書き換えておきましょう。

23
21
0

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
23
21