我添加了一种控制非订阅用户和订阅用户的小方法。基本上我的想法是所有使用 Devise 注册的用户都会获得一个帐户。但是,我的模型或根据找到的用户 ID 在数据库中存储的用户可以拥有的帖子数量应该是 25 个帖子。我猜下面的方法会起作用;
Model
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 分配给添加到数据库中的每个帖子。
我对上述函数的理解正确吗?或者我应该像这样将验证计数添加到我的刷新控制器/模型中;
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? %>
<span><%= @quota_warning %></span>
<% end %>
然后在模型上添加验证,以确保约束:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)