Running into problems where `user_id=' for nil:NilClass

I am trying to make a forum and i keep running into this problem. apparently the forum threads has an id but the forum msgs always returns a nil value. I have this in my controller: def create @forum_thread = current_user.forum_threads.new(forum_thread_params) @forum_thread.forum_msgs.first.user_id = current_user.id if @forum_thread.save redirect_to @forum_thread else render action: :new end end

Posted over 2 years ago by JrK
Posted over 2 years ago by JrK

def create
@forum_thread = current_user.forum_threads.new(forum_thread_params)
@forum_thread.forum_msgs.first.user_id = current_user.id
if @forum_thread.save
redirect_to @forum_thread
else
render action: :new
end
end

1
Posted over 2 years ago by Alex Yang

The nil:NilClass error you're seeing is because @forum_thread.forum_msgs.first isn't working as you intended. Instead of returning an object, it's returning nil. I would examine what @forum_thread.forum_msgs is returning - that will help you better understand why you're getting this nil response.

1
Posted over 2 years ago by JrK

yeah the @forum_threads doesn't return nil but the @forum_thread. forum_msgs does and I am not sure why this would happen. they both have the column in the database

1
Posted over 2 years ago by Alex Yang

You can check what objects are being returned. Immediately after 'def create', try using 'puts @forum_thread.inspect' or 'puts @forum_thread.forum_msgs.inspect'. You'll then be able to see the output of those commands in your Rails logs.

1