has_many, through : undefined method `id' for nil:NilClass
<p>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.</p>

<p>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: <em>undefined method `id' for nil:NilClass</em>  and it complains about this line: <em>@space_question = SpaceQuestion.new(question_id: params[:question_id], space_id: @space.id)</em></p>

<p>Here's my code:</p>

<p>spaces_controller.rb:</p>

<pre><code>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
</code></pre>

<p>space.rb:</p>

<pre><code>class Space &lt; 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
</code></pre>

<p>question.rb:</p>

<pre><code>class Question &lt; 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
</code></pre>

<p>space_question.rb:</p>

<pre><code>class SpaceQuestion &lt; ActiveRecord::Base
  belongs_to :space
  belongs_to :question
end
</code></pre>

<p>questions.html.erb: (within the spaces view)</p>

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