I want to develop a blog application. In which a user can create a post and comment on the post. A post can have many comments from user and it should belong to user. And, same way comment should belongs to user and blog. So, that I can identify which comment belongs to which post and which user has commented on post.
So, I have made association among models as below
class User < ApplicationRecord
has_many :comments
has_many :posts, through: :comments
end
class Post < ApplicationRecord
has_many :comments
has_many :users, through: :comments
end
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
end
Now, my question is how do I identify which user has created the post. I want to add a user_id in Post model, so that I can identify who is the author of Post.
Would it solve my problem?, if I write something like this in Post model
belongs_to :author, class_name: "User", foreign_key: "user_id"
How will migration files look?. I am looking for your suggestion and help. Is there a better way to associate these models?
Your help would be appreciated!