Steven Aguilar
Steven Aguilar

Reputation: 3049

Rails: create a relationship between comment and user

I'm trying to connect the create of a comment to the current_user. I have a model comment which is a polymorphic association.

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.string :content
      t.references :commentable, polymorphic: true
      t.timestamps
    end
  end
end

In the controller I'm trying to connect the @comment.user = current_user. controllers/comments_controller.rb

  def create
    @comment = @commentable.comments.new comment_params
    @comment.user = current_user
    @comment.save
    redirect_to @commentable, notice: 'Comment Was Created'
  end

But I get the following error:

NoMethodError: undefined method `user=' for # Did you mean? user_id=

I would rather set up a relationship from which I can get to a user (The creator of comment) from the comment itself. For example @comment.user instead of just having the id.

I have the following models:

class Question < ApplicationRecord
  belongs_to :user
  has_many :comments, as: :commentable
  has_rich_text :content
end

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts
  has_many :questions
  has_one_attached :avatar

  before_create :set_defaults

  def set_defaults
    self.avatar = 'assets/images/astronaut.svg' if self.new_record?
  end
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

Since comment is a polymorphic association, I'm not sure if it should be connected to user via a belongs_to to user.

[5] pry(#<Questions::CommentsController>)> @comment
=> #<Comment:0x00007fb3e6df72e8
 id: nil,
 content: "some test content",
 commentable_type: "Question",
 commentable_id: 1,
 created_at: nil,
 updated_at: nil,
 user_id: nil>
[6] pry(#<Questions::CommentsController>)>

Does this mean, I should create a foreign_key in the comments migration to a user? How can I go about getting the creator of the comment from the comment itself? Something like @comment.creator or @comment.user?

Upvotes: 0

Views: 370

Answers (1)

Gautam
Gautam

Reputation: 1812

In your user model add

has_many :comments

and in your comment model add

belongs_to :user

then you can do

@comment.user
@user.comments

but if you only want to get the user from comments and never the other way round then you can only add belongs_to :user in comment.

Upvotes: 3

Related Questions