Skip to content

Commit

Permalink
Merge pull request #2 from abdulhamiid/processing-data-in-models
Browse files Browse the repository at this point in the history
Processing data in models
  • Loading branch information
abdulhamiid authored Sep 24, 2022
2 parents 730c4f0 + 5032953 commit 394a03d
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 40 deletions.
9 changes: 9 additions & 0 deletions app/models/comment.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Comment < ApplicationRecord
belongs_to :author, class_name: 'User'
belongs_to :post
after_save :update_comments_counter

def update_comments_counter
post.increment!(:comments_counter)
end
end
9 changes: 9 additions & 0 deletions app/models/like.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Like < ApplicationRecord
belongs_to :author, class_name: 'User'
belongs_to :post
after_save :update_likes_counter

def update_likes_counter
post.increment!(:likes_counter)
end
end
14 changes: 14 additions & 0 deletions app/models/post.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :likes
has_many :comments
after_save :update_posts_counter

def update_posts_counter
author.increment!(:posts_counter)
end

def five_recent_comments
comments.order('created_at Desc').last(5)
end
end
9 changes: 9 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class User < ApplicationRecord
has_many :posts, foreign_key: 'author_id'
has_many :comments, foreign_key: 'author_id'
has_many :likes, foreign_key: 'author_id'

def recent_posts
posts.order('created_at Desc').last(3)
end
end
5 changes: 5 additions & 0 deletions db/migrate/20220924011718_rename_column_in_posts.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class RenameColumnInPosts < ActiveRecord::Migration[7.0]
def change
rename_column :posts, :user_id, :author_id
end
end
5 changes: 5 additions & 0 deletions db/migrate/20220924011808_rename_column_in_comments.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class RenameColumnInComments < ActiveRecord::Migration[7.0]
def change
rename_column :comments, :user_id, :author_id
end
end
5 changes: 5 additions & 0 deletions db/migrate/20220924011859_rename_column_in_likes.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class RenameColumnInLikes < ActiveRecord::Migration[7.0]
def change
rename_column :likes, :user_id, :author_id
end
end
78 changes: 38 additions & 40 deletions db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 394a03d

Please sign in to comment.