has_many,通过:nil:NilClass 的未定义方法“id”

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

我一直在尝试通过两个模型之间的关联添加一个 has_many; 'Space' 和 'Question'。在 space 内,您可以添加问题,这些问题将被列出来添加。我为协会创建了一个space问题模型。

目前,我能够看到要添加到 space 的所有问题的列表,但是当我尝试添加 space 时,我得到:未定义的方法` nil:NilClass 的 id' 并且它抱怨这一行: @space_question = SpaceQuestion.new(question_id: params[:question_id], space_id: @space.id)

这是我的代码:

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:(在 space 视图中)

<% @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 %>

除非您在该控制器中创建了一个 before 挂钩,否则您需要定义 @space 变量,add_question 方法中没有这样做。

您看到的错误正是它的意思。 @spacenil 而您正在呼叫 @space.id;因为 NilClass 没有方法 id,它会抛出一个错误。

如果您确实有定义该变量的钩子,请在

中编辑该代码