has_many,through:undefined method`id'为零:NilClass

时间:2016-05-06 18:42:21

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 activerecord

我一直试图通过两个模型之间的关联来添加一个has_many; '空间'和'问题'。在太空中,您可以添加将要添加的问题。我为关联创建了一个spaceQuestion模型。

目前,我能够看到要添加到空间的所有问题的列表,但是当我尝试添加空格时,我得到: undefined method`id'对于nil:NilClass 并且它抱怨这一行: @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 :(在空格视图中)

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

1 个答案:

答案 0 :(得分:0)

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

您所看到的错误正是它的含义。 @spacenil,您正在呼叫@space.id;由于NilClass没有方法id,因此会抛出错误。

如果你有一个定义该变量的钩子,请在

中编辑该代码
相关问题