Saleh Qadan Saleh Qadan - 6 months ago 26
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 = SpaceQuestion.new(question_id: params[:question_id], space_id: @space.id)

Here's my code:

spaces_controller.rb:

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

def add_question
@space_question = SpaceQuestion.new(question_id: params[:question_id], space_id: @space.id)

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


space.rb:

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


question.rb:

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
end


space_question.rb:

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


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

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

Answer

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 @space.id; 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

Comments