in rails how to limit users post count saved in database before asking to upgrade their account

前端 未结 1 1264
名媛妹妹
名媛妹妹 2021-01-16 08:47

I\'m adding a small way of controlling a non-subscribed user and a subscribed user. Basically my idea is that all users that sign up with the use of Devise, get an account.

相关标签:
1条回答
  • 2021-01-16 09:17

    I would use a before_filter on the corresponding controller(s):

    class PostsController < ApplicationController
      before_filter :check_quota # you could add here: :only => [:index, :new]
    
      private # optionnal
    
      def check_quota
        if user.posts.count >= 25
          @quota_warning = "You've reached maximum posts you can import"
        end
      end
    end 
    

    And in the view(s):

    <% if @quota_warning.present? %>
      <span><%= @quota_warning %></span>
    <% end %>
    

    Then add the validation on the model, to ensure the constraint:

    class Post < ActiveRecord::Base
      belongs_to :user
      before_save :check_post_quota
    
      private # optionnal
    
      def check_post_quota
        if self.user.posts.count >= 25
          self.errors.add(:base, "You've reached maximum posts you can import")
          return false
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题