Search code examples
ruby-on-railsrubydatabaseactiverecord

Association between post, user, and comment on Ruby on Rails


I'm trying to learn Ruby on Rails, an I'm kinda stuck with associaton. My project is to create a simple blog with three table. User, Post, and Comment.

In my understanding, after associationg several table with foreign key, rails would automatcily find user_id and post_id. But everytime I try to build comments, the user_id is nil.

Here's my model:

class User < ApplicationRecord
  has_many :posts
  has_many :comments
  
  validates :name, presence: true, length: { minimum: 5 }, uniqueness: true
  validates :password, presence: true, length: { minimum: 5 }
end
class Post < ApplicationRecord
  belongs_to :user
  has_many :comments

  validates :title, presence: true
  validates :body, presence: true, length: {minimum: 10}
end

class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :user
  
  validates :body, presence: true
  validates :user_id, presence: true
  validates :post_id, presence: true
end

Here is the screenshot when I try to create a comment: enter image description here

As you can see, the post_id is not nil but the user_id is nil.

I try to input user_id manualy and it work as intended. But I can't find out how to create comment with automatic user_id and post_id.


Solution

  • you can create a comments as below:

    user = User.find 2
    post = user.posts.where(id: 2).first
    comment = post.comments.build({comment_params}.merge(user_id: user.id))
    

    Hope this will help you.