【问题标题】:has_many, through : undefined method `id' for nil:NilClasshas_many,通过:nil:NilClass 的未定义方法“id”
【发布时间】:2016-05-06 18:42:21
【问题描述】:

我一直在尝试通过两个模型之间的关联来添加一个 has_many; “空间”和“问题”。在空间内,您可以添加将列出添加的问题。我为关联创建了一个 spaceQuestion 模型。

目前,我可以看到要添加到空格的所有问题的列表,但是当我尝试添加空格时,我得到:undefined method `id' for 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 %>

【问题讨论】:

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


【解决方案1】:

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

您看到的错误正是它的意思。 @spacenil 而你打电话给 @space.id;由于 NilClass 没有方法 id,因此会引发错误。

如果您确实有定义该变量的钩子,请在中编辑该代码

【讨论】:

  • 你的答案是正确的。我在同一个控制器中创建了一个 before 钩子,但没想到要重新检查该错误的代码。问题是我在 before_action 中不小心将 add_question 复数了。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多