Rails 3.1 limit user created objects

旧城冷巷雨未停 提交于 2019-12-17 10:29:56

问题


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

回答1:


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




回答2:


It did not work on Rails 3.2.1. Count always equals to 0. I have replaced it with self.user.things.size and now it works.



来源:https://stackoverflow.com/questions/7863618/rails-3-1-limit-user-created-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!