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.
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
comment is a polymorphic association, I'm not sure if it should be connected to user via a
 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>  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