Rails 3.1 限制用户创建的对象 [英] Rails 3.1 limit user created objects
本文介绍了Rails 3.1 限制用户创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想限制用户可以创建的模型对象的数量.我已经尝试了以下但它不起作用.我知道 rails 3.1 中发生了一些变化,现在不知道如何实现.
I would like to limit the number of model Objects a user can create. I've tried the below but it is not working. I understand some changes have happened in rails 3.1 and not sure how to accomplish this now.
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 进行了更新
Edit: updated for Rails 3
这篇关于Rails 3.1 限制用户创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文