在rails中如何限制用户在要求升级帐户之前保存在数据库中的帖子数 [英] in rails how to limit users post count saved in database before asking to upgrade their account
问题描述
我正在添加一种控制非订阅用户和订阅用户的小方法.基本上我的想法是所有使用 Devise 注册的用户都获得一个帐户.但是,我的模型或用户可以根据找到的用户 ID 存储在数据库中的帖子数量应该是 25 个帖子.我猜下面的方法会起作用;
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. However, my model or the number of posts a user can have in the database stored based on user ID found should be 25 posts. I'm guessing the following would work;
型号
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 是我正在做的事情,它抓取帖子并将这些帖子添加到数据库中的 current_user,或者将 current_user id 分配给它添加到数据库中的每个帖子.
:refresh is something I'm working on where it grabs posts and adds these posts to the current_user within the database, or assigns the current_user id to each post it adds to the database.
我对上述功能是否正确?或者我应该像这样将验证计数添加到我的刷新控制器/模型中;
am I correct on the above function? or should I add the validation count into my refresh controller/model like so;
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:
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
在视图中:
<% 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
这篇关于在rails中如何限制用户在要求升级帐户之前保存在数据库中的帖子数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!