9
16

More than 5 years have passed since last update.

[Rails]レコードの数を制限する

Posted at

Railsでレコードの数を制限する方法。

class Company < ActiveRecord::Base

 has_many :employees

end
class Employee < ActiveRecord::Base

 belongs_to :company

end

上記のようなケースで、Companyのemployeesの数にValidationをかけたい場合。

class Employee < ActiveRecord::Base

 belongs_to :company

 validate :check_number_of_employees

 def check_number_of_employees
  if company && company.employees.count > 10
   errors.add(:company, "人数OVER")
  end
 end

end

このようにかけます。

9
16
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
9
16