Rails的3.1限制用户创建的对象对象、用户、Rails

2023-09-09 21:58:53 作者:我们早已过了爱做梦的年纪

我要限制模式的数量对象的用户可以创建。我试过下面,但它不能正常工作。我明白了一些变化发生在轨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

为什么电脑没有家长控制,win7旗舰版

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

 
精彩推荐
图片推荐