Saleh Qadan Saleh Qadan - 1 year ago 81
Ruby Question

has_many, through : undefined method `id' for nil:NilClass

I've been trying to add a has_many, through association between two models; 'Space' and 'Question'. Within space, you are able to add questions which will be listed to add. I created a spaceQuestion model for the association.

Currently, I am able to see a list of all the questions to add to a space, but when I try adding a space I get: undefined method `id' for nil:NilClass and it complains about this line: @space_question = params[:question_id], space_id:

Here's my code:


def questions
@space_questions = @space.questions
@other_questions = (Question.all - @space_questions)

def add_question
@space_question = params[:question_id], space_id:

respond_to do |format|
format.html { redirect_to questions_tenant_space_url(id:, tenant_id: @space.tenant_id)
#notice: "User was successfully added to space"
format.html { redirect_to questions_tenant_space_url(id:, tenant_id: @space.tenant_id),
error: "Question was not added to space" }


class Space < ActiveRecord::Base
belongs_to :tenant
belongs_to :department
has_many :artifacts, dependent: :destroy

has_many :user_spaces, dependent: :destroy
has_many :users, through: :user_spaces

has_many :space_questions, dependent: :destroy
has_many :questions, through: :space_questions


class Question < ActiveRecord::Base
belongs_to :user
belongs_to :department

has_many :space_questions
has_many :spaces, through: :space_questions

validates_presence_of :title, :details, :department


class SpaceQuestion < ActiveRecord::Base
belongs_to :space
belongs_to :question

questions.html.erb: (within the spaces view)

<% @other_questions.each do |other_question| %>
<td><%= %></td>
<td><%= link_to other_question.title, question_path(other_question) %></td>
<td><%= %></td>
<%= link_to 'Add',
add_question_tenant_space_path(id:, tenant_id: @space.tenant_id, question_id:,
:method => :put,
:class => 'btn btn-xs btn-success' %>
<% end %>

Answer Source

unless you've created a before hook in that controller, you need to define the @space variable, which is not being done in the add_question method.

The error you're seeing is precisely what it means. @space is nil and you're calling; since the NilClass doesnt have a method id, it throws an error.

if you do have a hook defining that variable, please edit that code in