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

冷暖自知 提交于 2019-12-01 11:56:13

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