在rails中如何限制用户在要求升级其帐户之前保存在数据库中的post数

我正在添加一种控制非订阅用户和订阅用户的小方法。 基本上我的想法是所有使用Devise注册的用户都可以获得一个帐户。 但是,根据找到的用户ID,我的模型或用户在数据库中可以拥有的post数量应为25个post。 我猜这些会起作用;

模型

class Post belongs_to :user validate :quota, :on => :refresh def quota Posts = Posts.find(params[:id]) if user.posts.count >= 25 flash[:error] = "Sorry you need to upgrade" end end end 

:refresh是我正在努力抓取post的地方,并将这些post添加到数据库中的current_user,或者将current_user id分配给它添加到数据库的每个post。

我对上述function是否正确? 或者我应该将validation计数添加到我的刷新控制器/模型中,如此;

 class dashboard def refresh ... if self.user.posts.count >= 25 flash[:error] = "You've reached maximum posts you can import" end end end 

我会在相应的控制器上使用before_filter:

 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 

并在视图中:

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

然后在模型上添加validation,以确保约束:

 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