On rails, how to limit the number of user posts stored in the database before requesting an update to their account
I am adding a small way to manage unregistered user and subscriber. Basically my idea is that all users who sign up with Devise get an account. However, my model, or the number of posts a user can have in the database stored based on the user ID found, should be 25 posts. I am guessing the following will work;
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
: update is what I'm working on where it grabs messages and adds those messages to current_user in the database, or assigns the id current_user to every message added to the database.
Am I fixing this feature? or should I add a validation count to my update 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
+1
source to share
1 answer
I would use a before_filter file on the respective 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
And in views:
<% if @quota_warning.present? %>
<span><%= @quota_warning %></span>
<% end %>
Then add a model check to enforce 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
+1
source to share