问题描述
我添加了一种控制未订阅用户和已订阅用户的小方法。基本上我的想法是,所有使用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中如何限制用户在要求升级帐户之前发布保存在数据库中的帖子数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!