【问题标题】:Rails 3.1 limit user created objectsRails 3.1 限制用户创建的对象
【发布时间】:2011-12-13 09:34:20
【问题描述】:

我想限制用户可以创建的模型对象的数量。我已经尝试了以下方法,但它不起作用。我了解 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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-3.1 limit


    【解决方案1】:

    试试这样的:

    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 更新

    【讨论】:

    • 我正在使用 Rails 3.1 并获得“#<0x7fd94d9238e8>
    【解决方案2】:

    它不适用于 Rails 3.2.1。计数始终等于0。我已将其替换为 self.user.things.size,现在它可以工作了。

    【讨论】:

      猜你喜欢
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多