LoginSignup
3
4

More than 5 years have passed since last update.

Railsの1対多のmodelで子レコードに個数制限を設けたい

Last updated at Posted at 2016-09-18

こんな感じでどうだろう?

仕様

親(Shop)に子(Item)は3個までしか持てない

実装

親(Shop)

class Shop < ActiveRecord::Base
  has_many :items
  accepts_nested_attributes_for :items
  validate :items_size_validate

  ITEM_MAX = 3
  def items_size_validate
    errors.add(:items, "items over") if self.items.size > ITEM_MAX
  end
end

子(Item)

class Item < ActiveRecord::Base
  belongs_to :shop
  validate :shop_items_size_validate

  # 既にShopのitemが3つある時に、
  #   item = Item.new(shop_id: shop.id, name: 'item_4')
  # と、した場合にバリデーションできるように
  def shop_items_size_validate
    if self.shop && self.shop.items.size >= Shop::ITEM_MAX
      errors.add(:base, "items over")
    end
  end
end

かんそう

  • #shop_items_size_validate については、 Item.new を直接呼び出すのを、チーム内で禁止するだけでも良いかもしれない
3
4
4

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
3
4