0

我有一个包含帖子、评论和问题的项目。评论属于帖子,问题属于评论。我正在尝试显示属于页面评论的所有问题。但是,索引页面不显示任何问题。它没有给出错误,只是空白。

这是我的 questions_controller.rb:

   class QuestionsController < ApplicationController
 before_action :set_question, only: [:show, :edit, :update, :destroy]


def index
  @comment = Comment.find params[:comment_id]
  @comment.questions
end


def show
end


def new
  @comment = Comment.find params[:comment_id]
end


def edit
end


def create
  @comment = Comment.find(params[:comment_id])
  @question = @comment.questions.create(question_params)

  respond_to do |format|
    if @question.save
      format.html { redirect_to comment_questions_path, notice: 'Question was successfully created.' }
    format.json { render action: 'show', status: :created, location: comment_questions_path }
  else
    format.html { render action: 'new' }
    format.json { render json: @question.errors, status: :unprocessable_entity }
    end
  end
end

索引文件调用 _question.html.erb 部分:

<%=div_for(@question) do %>
<%= @question.body %>
<% end %>

index.html.erb 文件:

<%= render "questions/question" %>

最后,索引页面的链接如下所示:

<%= link_to 'View Questions', comment_questions_path(comment)%>

我已经检查过了,问题正在保存到数据库中,所以这不是问题。我真的很感激任何帮助。

4

2 回答 2

1

您的部分使用了未定义的变量,这是您的主要问题。但是您也不应该在局部变量中引用实例变量,因为这会增加局部变量和控制器之间的耦合。试试这个:

应用程序/视图/问题/_question.html.erb

<%= div_for(question) do %>
  <%= question.body %>
<% end %>

应用程序/视图/问题/index.html.erb

这就是真正的诀窍所在。通过将集合传递到部分中,我们能够自动迭代它,同时传递一个名为的局部变量question,这正是我们想要的。

<%= render @questions %>

有关使用部分渲染集合的更多信息,请参阅 Rails 指南页面上的布局和渲染

应用程序/控制器/questions_controller.rb

class QuestionsController < ApplicationController
  before_action :set_question, only: [:show, :edit, :update, :destroy]

  def index
    @comment = Comment.find params[:comment_id]
    @questions = @comment.questions
  end
end
于 2013-09-02T02:04:27.787 回答
0

您尚未在控制器中的任何位置定义 @question 变量,并且您正在视图中使用它,因此它将为空白并显示为空白。

在 questions_controller.rb 中试试这个代码

class QuestionsController < ApplicationController
 before_action :set_question, only: [:show, :edit, :update, :destroy]

  def index
    @comment = Comment.find params[:comment_id]
    @questions = @comment.questions
  end
  ...
end

并在视图中使用@questions 变量。

于 2013-09-02T01:46:42.610 回答