ruby-on-rails – Rails 3.1限制用户创建的对象

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 3.1限制用户创建的对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想限制用户可以创建的模型对象的数量.我已经尝试过以下但是没有用.我理解rails 3.1中发生了一些变化,现在还不确定如何实现.
  1. class User < ActiveRecord::Base
  2. has_many :things,:limit => 5,:dependent => :destroy # This doesn't work
  3. end
  4.  
  5. class Things <ActiveRecord::Base
  6. belongs_to :user
  7. end

解决方法

尝试这样的事情:
  1. class User < ActiveRecord::Base
  2. has_many :things
  3. end
  4.  
  5. class Things <ActiveRecord::Base
  6. belongs_to :user
  7. validate :thing_count_within_limit,:on => :create
  8.  
  9. def thing_count_within_limit
  10. if self.user.things(:reload).count >= 5
  11. errors.add(:base,"Exceeded thing limit")
  12. end
  13. end
  14. end

编辑:更新为Rails 3

猜你在找的Ruby相关文章