【发布时间】: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 %>
【问题讨论】:
-
你如何以及在哪里定义
@space? -
你为什么不用REST architecture?
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 activerecord