Rails 3.1 limit user created objects

前端 未结 2 877
北恋
北恋 2020-12-02 16:11

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

相关标签:
2条回答
  • 2020-12-02 16:37

    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

    0 讨论(0)
  • 2020-12-02 16:59

    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.

    0 讨论(0)
提交回复
热议问题