1

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

模型

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
4

1 回答 1

1

我会在相应的控制器上使用 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
于 2013-09-20T18:19:12.120 回答