add limit of post per day

This commit is contained in:
João Victor Geonizeli
2022-02-27 17:10:15 -03:00
parent 1d692b31f8
commit 7a24f7950b
4 changed files with 41 additions and 1 deletions

View File

@@ -5,6 +5,8 @@ class Post < ApplicationRecord
validates :content, length: { maximum: 777 } validates :content, length: { maximum: 777 }
validates :content, presence: true, if: :quoted_post? validates :content, presence: true, if: :quoted_post?
validate :user, :limit_of_post_per_day
def kind def kind
if quoted_post? if quoted_post?
:quoted_post :quoted_post
@@ -24,4 +26,12 @@ class Post < ApplicationRecord
def repost? def repost?
content.blank? && quoted_post_id content.blank? && quoted_post_id
end end
def limit_of_post_per_day
posts_from_day = user.posts.where('created_at >= ?', Time.zone.now.beginning_of_day)
if posts_from_day.count >= 5
errors.add(:base, 'You can post only 5 posts per day')
end
end
end end

View File

@@ -7,4 +7,6 @@ class User < ApplicationRecord
format: { format: {
with: /\A[a-zA-Z0-9]+\z/, with: /\A[a-zA-Z0-9]+\z/,
} }
has_many :posts
end end

View File

@@ -7,6 +7,8 @@ class UserFollow < ApplicationRecord
private private
def user_cant_follow_himself def user_cant_follow_himself
errors.add(:followed, 'can\'t follow himself') if follower_id == followed_id if follower_id == followed_id
errors.add(:followed, 'can\'t follow himself')
end
end end
end end

View File

@@ -28,4 +28,30 @@ RSpec.describe Post, type: :model do
end end
end end
end end
describe '#limit_of_post_per_day' do
context 'when user tries to post more than 5 times in a day' do
it 'returns error' do
user = create(:user)
5.times do
create(:post, user: user)
end
expect(build(:post, user: user).valid?).to be_falsey
end
end
context 'when the user has not yet reached their publication limit' do
it 'does not returns error' do
user = create(:user)
4.times do
create(:post, user: user)
end
expect(build(:post, user: user).valid?).to be_truthy
end
end
end
end end