17
19

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 3 years have passed since last update.

【Rails】has_manyの数を制限するvalidate

Last updated at Posted at 2020-05-15

例えば、Userが持てるPostの数を制限したいときは、Post側にvalidateを設定します。

user.rb
class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end
post.rb
class Post < ActiveRecord::Base
  MAX_POSTS_COUNT = 5

  belongs_to :user
  
  validate :posts_count_must_be_within_limit

  private

    def posts_count_must_be_within_limit
      errors.add(:base, "posts count limit: #{MAX_POSTS_COUNT}") if user.posts.count >= MAX_POSTS_COUNT
    end
end

これで、6個目のPostを作成しようとするとエラーになります。

ちなみに、Userにvalidateを定義した場合はUserをsaveしたときにvalidateが走ります。
つまり、Postのsave時にvalidateが効かず、6個目のPostを作れてしまうのでNGです。

user.rb
class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
  
  validates :posts, length: { maximum: 5 } # ←これでは`user.posts.create`のときに動かず、6個目のPostを作成できてしまう
end

環境

  • Ruby: 2.6.3
  • Rails: 6.0.2.2
17
19
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
17
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?