如何在视图中按ID订购模型?

时间:2016-09-03 23:23:49

标签: ruby-on-rails

我正在使用heroku来运行测验应用。

class Question
  belongs_to :quiz
end

class Answer
  belongs_to :question
end

所以我使用类似的东西生成测验:

<%  @questions.each do |question| %>

 // put questions here

  <% question.answers.each do |answer| %>

   // put answers here.

  <% end #answer.each do %>   

<% end #questions.each do %>

订购@questions很容易。在我的控制器中,我有:

@quiz = Quiz.find(params[:id])
@questions = @quiz.questions.order(:id)

所以只使用order(:id)我可以确保问题按照ID的顺序显示。我不知道以同样的方式订购答案的方法。

@answers = @questions.answers.order(:id)不起作用,因为我认为ruby不知道我正在使用哪个问题。我不能在我的has_many :answers, through: :questions模型中使用Quiz,因为对于每个问题,都会显示所有答案。我想以某种方式在我的视图中按ID排序答案,比如

question.answers.order(:id).each但是当我这样做时没有任何反应(因为Array可能没有订单方法?)我该怎么办?

2 个答案:

答案 0 :(得分:0)

这适用于您想要的吗?

    @questions.each do |question|  
      @answers = question.answers.order(:id)
    end

让我知道!

答案 1 :(得分:0)

因此,您建立关系的方式,每个问题都有一个方法答案,返回与问题相关的所有答案的列表。

因此,当您遍历每个问题时,您可以获得该答案列表,然后对其进行排序。

<%  @questions.each do |question| %>

// put questions here

  <% question.answers.order(:id).each do |answer| %>

   // put answers here.

  <% end #answer.each do %>  

<% end #questions.each do %>