遍历表并获取Rails中每个对象的最后一个元素

时间:2016-04-07 17:10:59

标签: ruby-on-rails associations

我在Rails上提出问题和答案。如何创建一个列出所有问题的页面,并在其下方显示该问题的最后答案?

这是我的答案控制器:

class AnswersController < ApplicationController
    def index
        @questions = Question.all
    end
end

问答模型:

class Answer < ActiveRecord::Base
    belongs_to :question
end

class Question < ActiveRecord::Base
    has_many :answers, dependent: :destroy
end

索引视图:

<% if @questions.blank? %>
    <p>No questions to display</p>
<% else %>
    <% @questions.each do |question| %>
        <h2><%= question.title %></h2>
        <!-- This is where the answer should appear.
        It should be the last answer in the question. -->
    <% end %>
<% end %>

我得到了出现的头衔但却无法让身体发挥作用。

我很抱歉这个糟糕的头衔,但是我不允许我写#34;问题&#34;在标题中。

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以试试这个 -

<% if @questions.blank? %>
  <p>No questions to display</p>
<% else %>
  <% @questions.each do |question| %>
    <h2><%= question.title %></h2>
    <!-- This is where the answer should appear.
    It should be the last answer in the question. -->
    <%= question.answers.last %>
  <% end %>
<% end %>