In my comments controller, I have the following
class CommentsController < ApplicationController
def create
@comment_hash = params[:comment]
#@comment = comment.new(comment_params)
@obj = @comment_hash[:commentable_type].constantize.find(@comment_hash[:commentable_id])
@comment = Comment.build_from(@obj, current_user.id, @comment_hash[:body])
binding.pry
#...
At the point where binding.pry is,
@comments_hash is
{"body=>"asdf comment body",
"commentable_type"=>"Hack",
"commentable_id"=>"2"}
@obj is
#<Hack id: 2, created_at: "2014-09-16 00:00:00",
updated_at: "2014-09-16 00:00:00",
body: "some text",
user_id: 1,
comment_threads_count: 0>
But @comment outputs
#<Comment id: nil,
commentable_id: 2,
commentable_type: "Hack",
title: nil, body: "asdf,
comment body",
subject: nil,
user_id: 1,
parent_id: nil,
lfg: nil, rgt:
nil, created_at: nil,
updated_at: nil>
Why are so many things nil here? All my arguments for the build_from method are identical to before, when the code worked properly.
The terminal output when attempting to call @comment.save is
undefined method 'user' for #<Comment:0x5d1b1b0>
I'm not sure what this means. I have a user_id association. I don't see a user param in my params hash.
Any help would be much appreciated.
@Substantial Your suspicion was correct.
Even though I the associations set up via the acts_as_commentable_with_threading method, I still had to do a
has_manybelongs_toassociation between the user and the comment. Once I added thehas_manybelongs_torelationship, things worked out. (and when I removed it again, it stopped working).having
acts_as_commentable_with_threadingin the user model is for posting comments on the user, not specifying that the comment belongs to the user. So if you want to post comments on users, you need both that method, ANDhas_many :comments&belongs_to :userin the comment modelIf you want just comments on another model, put the method in that model, and put
has_many :commentsin the user model, andbelongs_to :userin the comment model