ruby-on-rails – Rails 3.1限制用户创建的对象
发布时间:2020-12-16 19:24:57 所属栏目:百科 来源:网络整理
导读:我想限制用户可以创建的模型对象的数量.我已经尝试过以下但是没有用.我理解rails 3.1中发生了一些变化,现在还不确定如何实现. class User ActiveRecord::Base has_many :things,:limit = 5,:dependent = :destroy # This doesn't workendclass Things Active
我想限制用户可以创建的模型对象的数量.我已经尝试过以下但是没有用.我理解rails 3.1中发生了一些变化,现在还不确定如何实现.
class User < ActiveRecord::Base has_many :things,:limit => 5,:dependent => :destroy # This doesn't work end class Things <ActiveRecord::Base belongs_to :user end 解决方法
尝试这样的事情:
class User < ActiveRecord::Base has_many :things end class Things <ActiveRecord::Base belongs_to :user validate :thing_count_within_limit,:on => :create def thing_count_within_limit if self.user.things(:reload).count >= 5 errors.add(:base,"Exceeded thing limit") end end end 编辑:更新为Rails 3 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |