Rails的3.1限制用户创建的对象 [英] Rails 3.1 limit user created objects
本文介绍了Rails的3.1限制用户创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要限制模式的数量对象的用户可以创建。我试过下面,但它不能正常工作。我明白了一些变化发生在轨3.1和不知道现在该怎么做到这一点。
类用户的LT;的ActiveRecord :: Base的
的has_many:事情,:上限=> 5日:依赖=> :摧毁#这不工作
结束
一流的物联网<的ActiveRecord :: Base的
belongs_to的:用户
结束
解决方案
尝试是这样的:
类用户的LT;的ActiveRecord :: Base的
的has_many:事
结束
一流的物联网<的ActiveRecord :: Base的
belongs_to的:用户
验证:thing_count_within_limit,:上=> :创建
高清thing_count_within_limit
如果self.user.things(:重装).Count之间的> = 5
errors.add(:基地,超出限额的东西)
结束
结束
结束
修改:更新的Rails的3
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
解决方案
Try something like this:
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
Edit: updated for Rails 3
这篇关于Rails的3.1限制用户创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文