遍历 table 并获取 Rails 中每个 object 的最后一个元素
Iterate through table and get last element of each object in Rails
我正在 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 %>
我显示了标题,但无法使 body 正常工作。
我很抱歉标题不好,但是不允许我在标题中写 "question"。
谢谢!
你可以试试这个-
<% 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 %>
我正在 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 %>
我显示了标题,但无法使 body 正常工作。
我很抱歉标题不好,但是不允许我在标题中写 "question"。
谢谢!
你可以试试这个-
<% 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 %>