Home > Enterprise >  Ruby On Rails: Database model Associations
Ruby On Rails: Database model Associations

Time:08-15

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!

CodePudding user response:

What you are proposing will work, but your syntax seems backward.

I would expect @user.posts to return "posts that this user created", not "posts that have comments by this user"

I would expect @post.user to return "the user who authored this post", but you have @post.users returning "all users who commented on this post"

I would strive for these methods:

  • @user.posts returns all post this user created ("authored")

  • @user.comments returns all comments this user created

  • @user.commented_posts returns all posts this user has commented on

  • @post.user returns the user who created ("authored") this post

  • @post.comments returns all comments related to this post

  • @post.commented_users returns all users who have commented on this post

  • @comment.user returns the user who created this comment

  • @comment.post returns the post associated with this comment

By doing this:

class User < ApplicationRecord
  has_many :posts # "authored" posts
  has_many :comments
  has_many :commented_posts, through: :comments, source: :post
end

class Post < ApplicationRecord
  has_many :comments
  belongs_to :user # author
  has_many :commented_users, through: :comments, source: :user
end

class Comment < ApplicationRecord
 belongs_to :post
 belongs_to :user # commentor
end
  • Related